[英]how I should display the multiple item in the dropdown?
I want to display some multiple valus in dropdown with autocomplete我想通过自动完成在下拉列表中显示一些多个值
$(document).ready(function () {
$('#Client-ville_id').typeahead({
source: function (query, result) {
$.ajax({
url: "list_ville.php",
data: 'query=' + query,
dataType: "json",
type: "POST",
success: function (data) {
result($.map(data, function (item) {
return {
name: item.name,
cp:item.departement_code
}
}));
}
});
}
});
});
$sql = $conn->prepare("SELECT * FROM ville WHERE name LIKE ?");
$sql->bind_param("s",$search_param);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$countryResult[] = $row["name"];
$countryResult[] = $row["departement_code"];
}
echo json_encode($countryResult);
}
$conn->close();
But I get an error但我收到一个错误
Uncaught TypeError: Cannot read property 'name' of null at (index):531
未捕获的类型错误:无法读取 (index):531 处的 null 属性“名称”
The problem is that you're creating array with strings in php, you need问题是你在 php 中用字符串创建数组,你需要
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$countryResult[] = array(
"name" => $row["name"],
"departement_code" => $row["departement_code"]
);
}
echo json_encode($countryResult);
}
or just:要不就:
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$countryResult[] = $row;
}
echo json_encode($countryResult);
}
there is function that fetch all data in one function call, here is one for mysqli: mysqli_result::fetch_all .有一个函数可以在一个函数调用中获取所有数据,这里是 mysqli 的一个: mysqli_result::fetch_all 。
In your sql file do在你的 sql 文件中做
$sql = $conn->prepare("SELECT * FROM ville WHERE name LIKE ?");
$sql->bind_param("s",$search_param);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows > 0) {
$i = 0;
while($row = $result->fetch_assoc()) {
$countryResult[$i]['name'] = $row["name"];
$countryResult[$i]['departement_code'] = $row["departement_code"];
$i++;
}
echo json_encode($countryResult);
}
$conn->close();
The problem is that you create a non associative array, but reffer to it as associative.问题是您创建了一个非关联数组,但将其视为关联数组。
while($row = $result->fetch_assoc()) {
$countryResult[] = $row["name"];
$countryResult[] = $row["departement_code"];
}
After this loop $countryResult
array would like something like this在这个循环之后
$countryResult
数组会像这样
array(6) {
[0] => "name1"
[1] => "departement_code1"
[2] => "name2"
[3] => "departement_code2"
[4] => "name3"
[5] => "departement_code3"
}
You should change the while
loop:您应该更改
while
循环:
while($row = $result->fetch_assoc()) {
$countryResult[] = $row;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.