小编典典

jQuery UI使用JSON和Ajax自动完成

ajax

我已经看到许多有关通过JSON传递带有标签和值属性的数组的问题,但关于传递字符串的问题并不多。我的问题是我似乎无法填写自动填充内容。我运行了一个转储函数,并通过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);

我的自动完成功能保持空白。如何更改JSON数组以填充它?还是我的ajax成功函数中包含什么?


阅读 332

收藏
2020-07-26

共1个答案

小编典典

您可以非常坚持jQueryUI的自动完成功能的远程演示:http : //jqueryui.com/resources/demos/autocomplete/remote-
jsonp.html

为了使结果进入自动完成列表,您需要在ajax成功函数中放置一个带有标签和响应参数(实际上是一个函数)值的对象:

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

但这仅在您稍微修改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

2020-07-26