使用AutoCompletejQuery/ajax从php数组获取数据值

使用AutoCompletejQuery/ajax从php数组获取数据值,php,jquery,mysql,ajax,autocomplete,Php,Jquery,Mysql,Ajax,Autocomplete,我尝试使用devbridge autocomplete中的插件: 我希望从search.php页面中获得3个值,而不仅仅是1个值。 它适用于value,但不适用于data1和data2 result for each=null 我的jQuery代码: $('#search-adress').autocomplete({ serviceUrl: 'search.php', dataType: 'json', onSelect: function (value,data1,data2) {

我尝试使用devbridge autocomplete中的插件: 我希望从search.php页面中获得3个值,而不仅仅是1个值。 它适用于value,但不适用于data1和data2 result for each=null

我的jQuery代码:

$('#search-adress').autocomplete({
serviceUrl: 'search.php',
dataType: 'json',
onSelect: function (value,data1,data2) {
        alert('You selected: ' + value + ', ' + data1 + ', ' + data2);
    }
});
我的搜索页面:

$term=$_GET['query'];
$query = mysql_query("select distinct adress,id,city from myadresstable where (adress like '%{$term}%') order by adress limit 10 ");
if (mysql_num_rows($query))
{
    while($row = mysql_fetch_assoc($query))
    {
        $reply['suggestions'][] = ''.utf8_encode($row['nom_voie']).'';
        $reply['data1'][] = ''.utf8_encode($row['id']).'';
        $reply['data2'][] = ''.utf8_encode($row['city']).'';
    }
 echo json_encode($reply);
}

感谢您的帮助:

您只需通过以下方式更改一点php数组:

$term=$_GET['query'];
$query = mysql_query("select distinct adress,id,city from myadresstable where (adress like '%{$term}%') order by adress limit 10 ");
if (mysql_num_rows($query))
{
   $arr = array();
   while($row = mysql_fetch_assoc($query))
   {
     $reply['suggestions'] = utf8_encode($row['nom_voie']);
     $reply['data'] = utf8_encode($row['id']);
     $reply['value'] = utf8_encode($row['city']);
     $arr[] = $reply;
   }
   echo json_encode($arr);
}
在jquery代码中:

 $(function(){
 $('#autocomplete').autocomplete({
    lookup: datos,
    onSelect: function (suggestion) {
        console.log(suggestion);
         alert('You selected: ' + suggestion.value + ', ' + suggestion.data + ', ' + suggestion.nom_voie);
    }
  });
});
提琴样品: 尝试选择Valdivia以查看警报 我找到了解决办法:

问题是PHP数组。要使用此自动完成插件获取一些数据值,您必须使用数组:

PHP代码

$suggestions = array();
if (mysql_num_rows($query))
{
while($row = mysql_fetch_assoc($query))
{
 $mydata1='$row['data1']';
 $mydata2='$row['data2']';
$nom_voie=''.utf8_encode($row['nom_voie']).'';
$suggestions[] = array(
    "value" => $nom_mydata1,
    "data" => $nom_mydata2
);

    }
}
echo json_encode(array('suggestions' => $suggestions));

看看这个:Mys的问题在于devbridge的脚本,而不是jquery ui。您应该在php代码中使用json_encode:json_encode$reply;很抱歉,我放弃在这里写,但json_encode出现在我的源代码中。不幸的是,它不起作用。我在控制台类型错误上有一个错误:b在我尝试fiddle时未定义。它起作用,但结果是来自jquery代码的var[],而不是php代码。一个想法?你改变了你的php代码来匹配我的吗…如果你仔细看,我会稍微改变数组结构。