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

问题描述 投票:0回答:1

所以我有这个 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');
}

?>

欢迎任何建议。

php jquery ajax jquery-ui jquery-ui-autocomplete
1个回答
1
投票

看起来您正在返回一个数组,来自 jQuery API 参考数组类型定义状态

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']));
}   
© www.soinside.com 2019 - 2024. All rights reserved.