使用json和ajax的JQuery UI自动完成

我已经看到很多问题涉及通过JSON传递带有标签和值属性的数组,但关于传递字符串并不多。 我的问题是,我似乎无法填写自动填充function。 我运行了一个dump函数,并将这些样本值通过JSON传递给自动完成:

0: 23456 1: 21111 2: 25698 

这是一些代码:

 $("#auto_id").autocomplete( { source: function(request,response) { $.ajax ( { url: "fill_id.php", data: {term: request.term}, dataType: "json", success: function(data) { //what goes here? } }) } }); 

这是fill_id.php:

 $param = $_GET['term']; $options = array(); $db = new SQLite3('database/main.db'); $results = $db->query("SELECT distinct(turninId) FROM main WHERE turninid LIKE '".$param."%'"); while ($row_id = $results->fetchArray()) { $options[] = $row_id['turninId']; } echo json_encode($options); 

我的自动填充function仍为空白。 如何更改我的JSON数组以填充它? 或者我在ajax成功函数中包含哪些内容?

您可以非常关注jQuery UI的自动完成的远程演示: http : //jqueryui.com/resources/demos/autocomplete/remote-jsonp.html

要将结果放入自动完成列表,您需要将一个带有标签和值的对象放入ajax成功函数中的response参数(实际上是一个函数):

 source: function( request, response ) { $.ajax({ url: "fill_id.php", data: {term: request.term}, dataType: "json", success: function( data ) { response( $.map( data.myData, function( item ) { return { label: item.title, value: item.turninId } })); } }); } 

但这只有在你稍微修改yor fill_id.php时才有效:

 // escape your parameters to prevent sql injection $param = mysql_real_escape_string($_GET['term']); $options = array(); // fetch a title for a better user experience maybe.. $db = new SQLite3('database/main.db'); $results = $db->query("SELECT distinct(turninId), title FROM main WHERE turninid LIKE '".$param."%'"); while ($row_id = $results->fetchArray()) { // more structure in data allows an easier processing $options['myData'][] = array( 'turninId' => $row_id['turninId'], 'title' => $row_id['title'] ); } // modify your http header to json, to help browsers to naturally handle your response with header('Cache-Control: no-cache, must-revalidate'); header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); header('Content-type: application/json'); echo json_encode($options); 

当然,如果您的表格中没有标题或任何内容,您也可以保持原样,并在成功回调中重复ID。 重要的是,您在自动填充中使用值/项对填充response函数:

 // this will probably work without modifying your php file at all: response( $.map( data, function( item ) { return { label: item, value: item } })); 

编辑:更新了新jquery UI的自动完成ui的引用链接