我有一个selectAll函数,它将结果作为对象返回。
$customers = $app['database']->selectAll('customers');
以下是$ customers变量的var_dump:
array(4) {
[0]=> object(stdClass)#5 (7) { ["id"]=> string(2) "10" ["name"]=> string(10) "Thisted El" ["address"]=> string(13) "Otto Monsteds" ["city"]=> string(5) "Vej 8" ["phone"]=> string(9) "503982350" ["zip"]=> string(6) "481922" ["notes"]=> string(0) "" }
[1]=> object(stdClass)#6 (7) { ["id"]=> string(2) "11" ["name"]=> string(11) "Bibin Vinod" ["address"]=> string(8) "Kottayam" ["city"]=> string(5) "Kochi" ["phone"]=> string(10) "0294294022" ["zip"]=> string(6) "129042" ["notes"]=> string(0) "" }
}
我需要使用这些对象的'name'属性作为自动填充表单。我在this link中使用自动完成脚本。
在我的php文件中,我在表单后添加了上面的自动填充功能。然后我在这个对象上使用json_encode,然后是JSON.parse。我使用循环将名称添加到javascript数组,最后我将其传递给自动完成功能。
var js_data = '<?php echo json_encode($customers); ?>';
var js_obj = JSON.parse(js_data);
for (var i = 0; i < arrayLength; i++)
{
customername[i] = js_obj["name"];
}
autocomplete(document.getElementById("customers"), customername);
然而,自动填充表单不起作用。我想帮助解决这个问题。谢谢。
答案 0 :(得分:1)
我已经解决了这个问题。首先,我将对象数组转换为PHP中的普通数组:
$customers = $app['database']->selectAll('customers');
$allCustomers = array();
foreach($customers as $key => $val)
{
$allCustomers[] = $val;
}
然后在javascript部分,我在这个变量上使用了json encode
,并使用for循环将每个'name'属性添加到javascript数组中,最后同样将它传递给自动完成函数:
var js_data = <?php echo json_encode($allCustomers) ?>;
var customername = [];
for (var i = 0; i < js_data.length; i++)
{
customername[i] = js_data[i]["name"];
}
autocomplete(document.getElementById("customers"), customername);
非常感谢大家提供帮助。
答案 1 :(得分:0)
因为您只需要更改输入值而不是div DOM
document.getElementById("customers").value = customername;
答案 2 :(得分:0)
js_obj
是一个数组,您需要将其编入索引。
customername[i] = js_obj[i].name;
您也可以在PHP中创建一个名称数组。
$customers = array_map(function($x) {
return $x->name;
}, $app['database']->selectAll('customers'));
?>
var customers = <?php echo json_encode($customers; ?>;