循环访问数据以显示自动完成建议

Iterate over the data to show Autocomplete suggestions

本文关键字:访问 数据 显示 循环      更新时间:2023-09-26

这是一个在数组中返回结果的API,用于自动建议

例如,如果我查询"谷歌",我会得到如下结果

["google","google maps","google translate","google earth","google images","google docs","google voice","google scholar","google chrome","google calendar",]

你可以在这里自己尝试

这是我用来查询此 API 的代码,但它似乎没有返回结果。

这是我用于它的代码

     $(function() {
    $( "#city" ).autocomplete({
        source: function( request, response ) {
            $.ajax({
                url: "q.php",
                dataType: "json",
                data: {
                    "q" : request.term
                },
                success: function( data ) {
                    response(data[1]);
                }
            });
        },
        minLength: 2
    });
});

我不明白我在代码中哪里出错了请纠正我!因为它似乎没有像我想要的那样工作

编辑:从同一服务器访问数据

你忘了在你的小提琴中添加jquery-ui库。但是如果你这样做,代码无论如何都不起作用,因为你无法通过ajax请求访问来自另一个域的数据。仅来自 js 代码执行的同一域。

这可能会有所帮助

$(document).ready(function() {
$.getJSON('http://twitter.com/users/usejquery.json?callback=?', function(json) { //get information about the user usejquery from twitter api
$('#twitter_followers').text(json.followers_count); //get the follower_count from the json object and put it in a span
});
});

寻找称为跨域 ajax 的东西。http://usejquery.com/posts/the-jquery-cross-domain-ajax-guide

您可以在此处阅读有关将 jQuery autocomlete 用于跨域环境的信息: http://1300grams.com/2009/08/17/jquery-autocomplete-with-json-jsonp-support-and-overriding-the-default-search-parameter-q/

此外,您还需要将jquery.autocomplete.js添加到jsFiddle环境中。