使用autosuggest创建搜索框

时间:2016-02-20 11:08:24

标签: php api search-engine bing autosuggest

我正在尝试使用google / bing“autosuggest”功能创建一个搜索框。搜索过该网站后,我发现的最接近的位置是:Custom box with autocomplete from Google/Bing. Is there any way to read the received json file?

jsfiddle.net上的脚本效果很好,但是当我尝试复制代码时它不起作用。

这是我的代码:

<html>
<head>

<script>
$(function () {
    $("#hulk").autocomplete({
        source: function (request, response) {
            console.log("source");
            $.ajax({
                url: "http://api.bing.com/osjson.aspx?Query=" + encodeURIComponent(request.term) + "&JsonType=callback&JsonCallback=?",
                dataType: "jsonp",
                /*data: {
                "Query": request.term,
                "JsonType": "callback",
                "JsonCallback" : "?"
            },*/


                success: function (data) {
                    console.log("success!");
                    var suggestions = [];
                    $.each(data, function (i, val) {
                        console.log("suggestion: " + val);
                        suggestions.push(val);
                    });
                    response(suggestions);

                }
            });
        }
    });
});

</script>
</head>

<body>
<input type="text" id="hulk" />
 </body>
</html>

我在编码方面不是专家(主要是使用php),并且非常感谢任何帮助使这项工作:)

提前致谢!

1 个答案:

答案 0 :(得分:0)

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/js/standalone/selectize.min.js" integrity="sha256-+C0A5Ilqmu4QcSPxrlGpaZxJ04VjsRjKu+G82kl5UJk=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/css/selectize.bootstrap3.min.css" integrity="sha256-ze/OEYGcFbPRmvCnrSeKbRTtjG4vGLHXgOqsyLFTRjg=" crossorigin="anonymous" />
</head>
<body>
  <select id="select-state" placeholder="Pick a state...">
    <option value="">Select a state...</option>
    <option value="AL">Alabama</option>
    <option value="AK">Alaska</option>
    <option value="AZ">Arizona</option>
    <option value="AR">Arkansas</option>
    <option value="CA">California</option>
    <option value="CO">Colorado</option>
    <option value="CT">Connecticut</option>
    <option value="DE">Delaware</option>
    <option value="DC">District of Columbia</option>
    <option value="FL">Florida</option>
    <option value="GA">Georgia</option>
    <option value="HI">Hawaii</option>
    <option value="ID">Idaho</option>
    <option value="IL">Illinois</option>
    <option value="IN">Indiana</option>
  </select>
</body>
</html>
<script>
$(document).ready(function () {
      $('select').selectize({sortField: 'text'});});</script>