繁体   English   中英

使用json和ajax进行JQuery UI自动完成

[英]JQuery UI autocomplete with json and 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成功函数中包含哪些内容?

您可以非常关注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的引用链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM