javascript - AJAX:我如何绑定(bind) KeyUp 上的自动完成功能才能使用键盘键

标签 javascript jquery html ajax jquery-ui

我如何将所谓的“自动完成”功能绑定(bind)或使用到下面的代码,以便使用自动完成功能键盘向上、向下和输入功能,因为目前我的代码没有该功能。它位于 WordPress 模板上,目前仅由鼠标控制。

<script>
$(document).ready(function(){
    $("#search-box").keyup(function(){
        $.ajax({
            type: "POST",
            url: "autocomplete.php",
            data:'keyword='+$(this).val(),        
            success: function(data){
                $("#suggesstion-box ").show();
                $("#suggesstion-box").html(data);               
            }
        });  
    }); 
});

function selectCountry(val) {
  $("#search-id").val(val);
  $("#suggesstion-box").hide();
}

function updateSearchBox(el) {
  $("#search-box").val($(el).html());   
}
</script>

我尝试过使用

 $("#search-box").keyup.autocomplete(function() {  

 $("#search-box").autocomplete(function() { 

甚至

 $("#search-box").autocomplete.keyup(function() { 

但它并没有拉出列表。我知道我的 AJAX 有问题导致我遇到键盘无法正常工作的问题。有什么建议么?

好的...我已经更改了我的 php 以给出 json。

自动完成.php

<?php
include_once "functions.php";

     if(isset($_POST['keyword']))
    {
        $database = lookup_connectToDatabase();                     
        $result = pg_query($database, "SELECT country, id, state FROM customers WHERE country iLIKE '" . $_POST["keyword"] . "%' OR id iLIKE '" . $_POST["keyword"] . "%' ORDER BY country");

        if (!$result){
                echo "<div class='show' align='left'>No matching records.</div>";
        }else {

            while($row=pg_fetch_assoc($result)){

                $array[] = array(
                    'label' = $row['id'].': '.$row['country'].', '.$row['state'],
                    'value' = $row['id'],
                );

            } 
            echo json_encode ($array);
        }
    }                                                   
?>

但似乎仍然无法正常工作。这个 json 我缺少什么?

最佳答案

我怀疑您正在寻找:http://jqueryui.com/autocomplete/#remote

在您的脚本中,这可能如下所示:

$(document).ready(function(){
    $("#search-box").autocomplete({
        minLength: 0,
        source: "autocomplete.php",
        select: function(e, ui){
            $("#search-box").val(ui.item.label);
            $("#search-id").val(ui.item.value);
            return false;
        }
    });
});

查看更多:http://api.jqueryui.com/autocomplete/#option-source

String: When a string is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data. It can be on the same host or on a different one (must provide JSONP). The Autocomplete plugin does not filter the results, instead a query string is added with a term field, which the server-side script should use for filtering the results. For example, if the source option is set to "http://example.com" and the user types foo, a GET request would be made to http://example.com?term=foo. The data itself can be in the same format as the local data described above.

如果必须使用POST,也可以这样做,但是有点复杂。

Function: The third variation, a callback, provides the most flexibility and can be used to connect any data source to Autocomplete.

这可能看起来像:

$(document).ready(function(){
    $("#search-box").autocomplete({
        minLength: 0,
        source: function(req, resp){
            $.ajax({
                type: "POST",
                url: "autocomplete.php",
                data:'keyword=' + req.term,
                success: function(d){
                    resp(d);
                }
            });
        },
        select: function(e, ui){
            $("#search-box").val(ui.item.label);
            $("#search-id").val(ui.item.value);
            return false;
        }
    });
});

这些示例未经测试,因为您没有提供示例数据。

更新

根据您的 autocomplete.php 文件,我建议如下:

<?php
include_once "functions.php";

if(isset($_POST['keyword'])){
    $database = lookup_connectToDatabase();
    $result = pg_query($database, "SELECT country, id, state FROM customers WHERE country iLIKE '" . $_POST["keyword"] . "%' OR id iLIKE '" . $_POST["keyword"] . "%' ORDER BY country");
    $data = array();
    if ($result){
        while($row=pg_fetch_assoc($result)){
            $data[] = array(
                "label" => $row['country'].', '.$row['state'],
                "value" => $row['id'],
            );
        } 
    }
    header('Content-Type: application/json');
    echo json_encode ($array);
}
?>

这应该返回一个具有 labelvalue 属性的对象数组。

The label property is displayed in the suggestion menu. The value will be inserted into the input element when a user selects an item. If just one property is specified, it will be used for both, e.g., if you provide only value properties, the value will also be used as the label.

如果没有匹配项,我们将只得到一个空数组作为返回。假设我们收到以下响应:

[
  {
    "label": "United States, California",
    "value": 420 
  },
  {
    "label": "United States, New York",
    "value": 100 
  }
]

当选择其中之一时,将执行select回调,并且#search-box将收到ui.item.label#search-id 将接收 ui.item.value

关于javascript - AJAX:我如何绑定(bind) KeyUp 上的自动完成功能才能使用键盘键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41403444/

相关文章:

javascript - D3 不显示 SVG 文本元素

java - Struts 2 中的澄清

javascript - 如何重置受 jquery 函数影响的元素

html - 屏幕阅读器在到达 span 元素时停止

javascript - JQuery 根据 iframe 源设置 iframe 高度

javascript - 如何使用 Javascript 使用每个元素自己的高度将 margin-bottom 添加到具有类的所有元素?

jQuery 剪贴板复制

php - jQuery - click() 在附加到在 PHP 中创建的 anchor 时不起作用

html - 两个谷歌地图重叠

javascript - 在 Angular js 中嵌入来自 json 响应的 Youtube 视频 url 和 Vimeo 视频 url 时的问题