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

时间:2013-07-20 17:03:44

标签: php jquery jquery-ui jquery-autocomplete

我从php返回一个JSON编码数组:echo(json_encode($data));,我希望它从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'];

5 个答案:

答案 0 :(得分:4)

尝试使用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响应示例

<?php
header('Content-type: application/json');
echo '{"items":[{"name":"Ashok"},{"name":"Rai"},{"name":"Vinod"}]}';
?>

<强> Demo Fiddle

<强> Remote JSONP Demo

答案 1 :(得分:2)

来自php的正确的json格式:

<?php
   echo '[ {"name1":"val1"},{"name2":"val2"} ]'; 
?>

来自js,意思是[] -array of {}对象。

在我的autocomlete widjet案例中,这很好用:

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

    echo $response;

答案 2 :(得分:0)

源参数可能有问题。应该是'/Searchtest.php'吗?

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

答案 3 :(得分:0)

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

isset

答案 4 :(得分:0)

<html>
    <head>
            <title>Ajax</title>
            <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
            <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
            <script>
                 $(function() { 
                    $("#myname").autocomplete({
                      source: 'emp.php',
                      select: function (event, ui) {
                        $("#myname").val(ui.item.label);
                        $("#myid").val(ui.item.id);
                    },
                       minLength: 0,
                       autoFocus: true,
                    }); 
                });
            </script>
    </head>
    <body>
        <h2>Ajax Testing</h2>
        <input  name="myname" id="myname" type="text">
        <input  name="myid" id="myid" type="text">
    </body>
</html>
-------------- Below is the code of PHP for emp.php page --------------------------
<?php
require_once 'connection.php';
$query  = "SELECT myname as label , myid as id  FROM emp WHERE name LIKE ? ORDER BY name";
$rsTable = sqlsrv_query($conn, $query,array('%'.$_REQUEST['term'].'%'));
while ($row_rsTable = sqlsrv_fetch_array($rsTable, SQLSRV_FETCH_ASSOC)) {

    $emparray[] = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $row_rsTable);
}
echo json_encode($emparray);
sqlsrv_close($conn);
?>