jQuery自动完成显示ID而不是名称

时间:2014-02-13 14:30:06

标签: jquery-ui

所以我有这个jQuery脚本从数据库中提取内容,需要来显示产品名称(我的表有productid和productname)。但它不显示产品名称,而是显示产品ID。我该如何解决这个问题?

这是jQuery代码: -

<script>
  $(function() {
    function log( message ) {
      $( "<div>" ).text( message ).prependTo( "#log" );
      $( "#log" ).scrollTop( 0 );
    }

    $( "#birds" ).autocomplete({
      source: "search.php",
      minLength: 2,
      select: function( event, ui ) {


        log( ui.item ? "Selected: " + ui.item.actor + " aka " + ui.item.label :
          "Nothing selected, input was " + this.actor );
       // window.location.href = 'pretravel.php?id=' + ui.item.label;
       // document.testForm.action = "pretravel.php?id="+ui.item.value;
        //document.testForm.submit();
      }
    });
  });



  </script>

这是 search.php

<?php
include 'dbconnector.php';

// Sanitise GET var
if(isset($_GET['term']))
{
$term = mysql_real_escape_string($_GET['term']);
// Add WHERE clause
//$term="Apple";
$query = "SELECT `productid`, `productname` FROM `products` WHERE `productname` LIKE '%".$term."%' ORDER BY `productid`";


$result = mysql_query($query,$db) or die (mysql_error($db));
$id=0;
$return=array();
while($row = mysql_fetch_array($result)){

    array_push($return,array('label'=>$row['productid'],'actor'=>$row['productname']));
    //array_push($return,array('actor'=>$row['productname'],'label'=>$row['productid']));

}

header('Content-type: application/json');
echo json_encode($return);
//var_dump($return);

exit(); // AJAX call, we don't want anything carrying on here
}
else
{
    header('Location:index');
}

?>

欢迎任何建议。

1 个答案:

答案 0 :(得分:1)

看起来你要返回一个数组,从数组类型定义的jQuery API reference状态An array of objects with label and value properties

因此,如果您更改search.php页面以返回这些类型,则应该有效:

while($row = mysql_fetch_array($result))
{
   array_push($return,array('value'=>$row['productid'],'label'=>$row['productname']));
}