【问题标题】:JQuery Autocomplete, populate with data from pHp jsonJQuery 自动完成,使用来自 pHp json 的数据填充
【发布时间】:2013-07-19 19:53:53
【问题描述】:

我从 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'];

【问题讨论】:

  • 你得到什么错误?你能粘贴你的PHP代码吗,你的JS代码看起来还可以。
  • 没有错误。我刚刚意识到我没有向 SearchTest.php 发送任何内容。我将如何发布到服务器并检索 JSON 以填充自动完成?
  • 你能告诉我你的php代码吗?

标签: php jquery jquery-ui jquery-autocomplete


【解决方案1】:

尝试使用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

【讨论】:

  • 继续执行 .fail 函数
  • 这意味着来自 SearchTest.php 的响应不是正确的JSON 格式,更新了答案,添加了method: 'post',JSON 格式和演示小提琴
  • 我什至试过 echo '{"items":[{"name":"Ashok"},{"name":"Rai"},{"name":"Vinod"}]} ';在 php 方面,但仍然没有。
  • 还有这个:$json = '{"items":[{"name":"Ashok"},{"name":"Rai"},{"name":"Vinod"} ]}'; echo json_decode($json);
  • 在 echo 之前通过添加 header('Content-type: application/json'); 将内容类型添加到 json 并确保在 header 函数之前没有 echowhite spaceplan text
【解决方案2】:

来自 php 的正确 json 格式:

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

来自 js 意味着 {} 对象的 []-array。

在我的自动完成widjet的情况下,这工作正常:

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

    echo $response;

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

      这样的事情是最好的方法。 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);
      

      【讨论】:

        【解决方案5】:
        <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);
        ?>
        

        【讨论】:

        • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助、质量更好,并且更有可能吸引投票
        猜你喜欢
        • 1970-01-01
        • 2015-12-13
        • 2021-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-09
        • 1970-01-01
        • 2011-11-16
        相关资源
        最近更新 更多