自动完成jquery不工作,它显示所有数据

时间:2016-07-18 08:28:56

标签: jquery json

我想用jquery插件制作自动完成输入标签,但它显示所有数据而不是搜索关键字。下面是我的html代码,js和json源代码

xml.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>jQueryUI Auto Complete</title>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
    <link rel="stylesheet" href="/resources/demos/style.css">
    <style>
    .ui-autocomplete-loading {
        background: white url("images/ui-anim_basic_16x16.gif") right center no-repeat;
    }
    </style>
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
    <script src="js/suggestionBox.js"></script>
    <script>

    </script>
</head>
<body>

<div class="ui-widget">
    <label for="birds">London matches: </label>
    <input class="content2" id="txtFastQuote" name="txtFastQuote" size="20" ">
</div>

<div class="ui-widget" style="margin-top:2em; font-family:Arial">

    <div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>


</body>
</html>

这是我的Suggestion Box.js,我把我的javascript代码

$(document).ready(function () {
            $("#txtFastQuote").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: "countries.json",
                        dataType: "json",
                        type: "POST",
                        success: function (data) {
                            response($.map(data, function (item) {
                                return {
                                    label: item.name,
                                    value: item.code
                                }
                            }))
                        },
                        error: function (a, b, c) {
                            debugger;
                        }
                    });

                },
                minLength: 1
            });
        });

我的countries.json文件

[ 
  {"name": "Afghanistan", "code": "AF"}, 
  {"name": "Albania", "code": "AL"}]

1 个答案:

答案 0 :(得分:0)

尝试使用此代码,

$(document).ready(function () {
        $("#txtFastQuote").autocomplete({
            source: function(request, response) {
                $.getJSON('data/countries.json', { q: request.term }, function(data) {
                    response($.map(data.destinations, function(item) {
                        return item.name;
                    }));
                });
            }
        });

    });