【问题标题】:Get data value from php array with autocomplete jquery/ajax使用自动完成 jquery/ajax 从 php 数组中获取数据值
【发布时间】:2015-06-03 20:45:27
【问题描述】:

我尝试使用“devbridge autocomplete”中的插件:https://www.devbridge.com/sourcery/components/jquery-autocomplete/ 我想从我的 search.php 页面中获取 3 个值(而不仅仅是 1 个)。 它适用于“value”,但不适用于“data1”和“data2”(每个 = 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);
}

谢谢你帮助我:)

【问题讨论】:

  • 我的问题在于 devbridge 的脚本而不是 jquery-ui
  • 你应该在你的 php 代码中使用json_encodejson_encode($reply);
  • 对不起,我忘了写在这里,但我的源代码中有 json_encode。

标签: php jquery mysql ajax autocomplete


【解决方案1】:

您可以通过这种方式稍微更改 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);
    }
  });
});

小提琴样例:https://jsfiddle.net/robertrozas/n6oLLfmc/

  • 尝试选择“Valdivia”以查看警报

【讨论】:

  • 不幸的是它不起作用我在控制台上出现错误“TypeError:b未定义”当我尝试使用小提琴时它可以工作,但结果是来自jquery代码而不是php代码的var [] .一个想法?
  • 您是否更改了您的 php 代码以匹配我的...如果您仔细观察,我会稍微更改数组结构。
【解决方案2】:

我找到了解决方案:)

问题出在PHP 数组上。要使用此自动完成插件获取一些数据值,您必须使用 array()

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));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-22
    • 1970-01-01
    • 2012-07-31
    • 1970-01-01
    • 2013-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多