Javascript 我应该如何在下拉列表中显示多个项目?

Javascript 我应该如何在下拉列表中显示多个项目?,javascript,jquery,Javascript,Jquery,我想用autocomplete在下拉列表中显示一些多个值 $document.readyfunction{ $'Client-ville\u id'。提前键入{ 来源:函数查询,结果{ $.ajax{ url:list_ville.php, 数据:“查询=”+query, 数据类型:json, 类型:POST,, 成功:函数数据{ 结果$.mapdata,函数项{ 返回{ 名称:item.name, cp:item.Department\U代码 } }; } }; } }; }; $sql=$c

我想用autocomplete在下拉列表中显示一些多个值

$document.readyfunction{ $'Client-ville\u id'。提前键入{ 来源:函数查询,结果{ $.ajax{ url:list_ville.php, 数据:“查询=”+query, 数据类型:json, 类型:POST,, 成功:函数数据{ 结果$.mapdata,函数项{ 返回{ 名称:item.name, cp:item.Department\U代码 } }; } }; } }; }; $sql=$conn->prepareSELECT*从名称类似的地方选择?; $sql->bind_参数,$search_参数; $sql->execute; $result=$sql->get\u result; 如果$result->num_rows>0{ 而$row=$result->fetch\u assoc{ $countryResult[]=$row[name]; $countryResult[]=$row[部门代码]; } echo json_编码$countryResult; } $conn->close; 但我犯了个错误

未捕获的TypeError:无法读取索引531处null的属性“name”


问题是,在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);
}
或者只是:

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $countryResult[] = $row;
    }
    echo json_encode($countryResult);
}
有一个函数可以在一次函数调用中获取所有数据,下面是一个用于mysqli:。

在您的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();

问题是您创建了一个非关联数组,但将其作为关联数组引用

while($row = $result->fetch_assoc()) {
    $countryResult[] = $row["name"];
    $countryResult[] = $row["departement_code"];
}
在这个循环之后,$countryResult数组会像这样

array(6) {
  [0] => "name1"
  [1] => "departement_code1"
  [2] => "name2"
  [3] => "departement_code2"
  [4] => "name3"
  [5] => "departement_code3"
}
您应该更改while循环:


在该解决方案中,他将只获得最后一个元素,因为$countryResult['name']每次都将被覆盖。是的,我更新代码以防止覆盖记录@Krzysztof Janiszewskiyes,它可以工作,但不会通过示例显示同一输入上的两个项,结果$.mapdata,函数项{name:item.name;cp:item.department_code;返回名称+'-'+cp;};已创建结果$.mapdata,函数项{return item.name+'-'+item.department_code;};但另一个pb/It显示巴黎未定义
while($row = $result->fetch_assoc()) {
    $countryResult[] = $row;
}