JQuery Autocomplete,填充来自pHp json的数据

我正在返回一个JSON编码的数组: echo(json_encode($data)); 从PHP,我希望它从JQuery自动完成填充建议框。 我正在使用这个:

 $("#field").autocomplete({ source : "SearchTest.php", maxLength: 5 }); 

不知道为什么这不起作用。 每次按键后,我都会检索数据并用这些数据填充建议框,我不希望自动完成排序并为我选择,我正在做那个服务器端。 它现在只是一个字符串列表。 能够自定义数据的呈现方式也很不错。

编辑:将来源更改为发布:

 $("#field").autocomplete({ source : function(request, response) { $.post("SearchTest.php", request, response); }, maxLength : 5 }); 

立即获得此错误:

 Uncaught TypeError: Cannot use 'in' operator to search for '1240' in Notice: Undefined index: field in /.../SearchTest.php on line 25 

第25行是: $whatTheyWantToSearch = $_POST['field'];

尝试使用ajax

 var searchRequest = null; $("#field").autocomplete({ maxLength: 5, source: function(request, response) { if (searchRequest !== null) { searchRequest.abort(); } searchRequest = $.ajax({ url: 'SearchTest.php', method: 'post', dataType: "json", data: {term: request.term}, success: function(data) { searchRequest = null; response($.map(data.items, function(item) { return { value: item.name, label: item.name }; })); } }).fail(function() { searchRequest = null; }); } }); 

SearchTest.php中的JSON响应示例

  

演示小提琴

远程JSONP演示

从PHP的适当的json格式:

  

从js开始,意味着[] -array of {}对象。

在我的autocomlete widjet的情况下,这工作正常:

  $response="["; while($row = $res->fetch_assoc()){ if($response !="[")$response.=","; $response.='{"label":"'.$row["fio"].'","value":"'.$row["id"].'"}'; } $response.="]"; echo $response; 

也许source参数有问题。 应该是’/Searchtest.php’吗?

http://api.jqueryui.com/autocomplete/#option-source

这样的事情是最好的方式。 json_encode一切都适合你。

  $result = $_mysqli->query(...); $rs = array(); $pos = 0; while($row = $result->fetch_assoc()){ $rs[$pos]["n1"] = $row["n1"]; $rs[$pos]["n2"] = $row["n2"]; ... $rs[$pos++]["nn"] = $row["nn"]; } header('Content-type: application/json'); echo json_encode($rs);