jQuery UI 自动完成 - 输入与结果集不匹配时不显示结果

发布于 2024-11-07 15:11:10 字数 1925 浏览 0 评论 0原文

问题自动完成的简短版本

当输入字符串与结果字符串匹配时, 起作用,但否则不起作用。已成功从 JSON 检索数据。

更长的版本

我想用 JSON 数据动态编辑自动完成的源内容。

当搜索字符串与first_name 和last_name 字段匹配时,以下方法有效。

但 JSON url 返回更多,例如,通过用户名搜索,它仍然返回正确的数据。但这并没有在自动完成中显示出来,我的理论是自动完成 UI 强制“输入值”与“结果值”相同

JSON 数据返回:

[
        {"pk": 1012912, "fields": {"first_name": "Barack", "last_name": "Obama"}}, 
        {"pk": 1017519, "fields": {"first_name": "George", "last_name": "Bush"}}
]

自动完成代码

如您所见,结果集是由搜索功能设置的。


$('#search').autocomplete({
    source: [],
    search: function(event, ui){
        results = [];
        var json = jQuery.getJSON('http://jsondata.com?query='+event.target.value, function(data){
            for (var i=0; i<data.length; i++){
                results.push(data[i].fields.first_name + ' ' +data[i].fields.last_name); 
            };
        }).success(function(){
            $('#search').autocomplete('option', 'source', results);
            //The following debug proves that the 'results' are correct, even on search for usernames
            console.log(results);
        });
    },
});

如果我在#search 字段中搜索“Barack Obama”,我会得到结果,没问题。 但是,如果说 Barack Obama 的用户名是“baracko”,并且我搜索他的用户名,那么我会从 JSON 和结果数组中获得正确的结果(正如我使用 console.log 检查的那样),但结果不会显示。

有人知道为什么吗?

为未来的谷歌用户或感兴趣的人提供的解决方案

感谢 ek_ny 的一些提示,这是我的新 JSON:

[{ 'value' : 'Barack Obama'}, { 'value' : 'George Bush'}]

这是代码:

$('#search').autocomplete({
    source: function(req, res){
        jQuery.getJSON('http://jsondata.com/?query='+req.term, req, function(data){  
            var results = [];
            $.each(data, function(i, val){
                results.push(val.value)
            });
            //Add results to callback       
            res(results);
        });           
    },
});

Short version of Problem

Autocomplete works when the input string matches the result string, but not otherwise. The data are succesfully retreived from JSON.

Longer version

I want to dynamicly edit the source content of the autocomplete with JSON data.

The approach below works when the search string matches the first_name and last_name field.

But the JSON url returns more, e.g. with search on username it still returns correct data. But this is not shown in autocomplete, and my theory is that autocomplete UI forces the 'input value' to be the same as the 'result value'.

JSON data returns:

[
        {"pk": 1012912, "fields": {"first_name": "Barack", "last_name": "Obama"}}, 
        {"pk": 1017519, "fields": {"first_name": "George", "last_name": "Bush"}}
]

The autocomplete code

As you can see the result set is set by the search function.


$('#search').autocomplete({
    source: [],
    search: function(event, ui){
        results = [];
        var json = jQuery.getJSON('http://jsondata.com?query='+event.target.value, function(data){
            for (var i=0; i<data.length; i++){
                results.push(data[i].fields.first_name + ' ' +data[i].fields.last_name); 
            };
        }).success(function(){
            $('#search').autocomplete('option', 'source', results);
            //The following debug proves that the 'results' are correct, even on search for usernames
            console.log(results);
        });
    },
});

If I search for 'Barack Obama' in the #search field, I get my results, no problem.
However, if say Barack Obama had the username 'baracko' and I search for his username, then I get the correct results from the JSON and in the results array (as I checked this with console.log) but the results are not shown.

Anyone have the idea why?

Solution for future googlers or those intrested

Thanks to some hints by ek_ny here is my new JSON:

[{ 'value' : 'Barack Obama'}, { 'value' : 'George Bush'}]

And here is the code:

$('#search').autocomplete({
    source: function(req, res){
        jQuery.getJSON('http://jsondata.com/?query='+req.term, req, function(data){  
            var results = [];
            $.each(data, function(i, val){
                results.push(val.value)
            });
            //Add results to callback       
            res(results);
        });           
    },
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

╭⌒浅淡时光〆 2024-11-14 15:11:10

我不知道这是否有帮助,但我的自动完成设置有点不同。我使用 source 属性,它允许我控制对 jQuery 的回调。我的 ajax 调用返回 [{"id":1, "label": "Annie Hall",.....] 形式的项目。您可以根据需要修改 Ajax 调用的结果,具体取决于数据从服务器返回的方式。这是我用来调用它的代码。

        $("#movieSearch").autocomplete({
            source: function(req, res){
                $.getJSON(
                    "search.aspx",
                    {term : req.term},
                    function(data){
                        res(data);//you can also modify your results before you call res()
                    }
                );
            }
);

你的例子中让我困扰的一件事是变量结果,在我看来,它是一个全局变量。我们都知道(用 Douglas Crockford 的话说)全局变量是邪恶的。

I don't know if this helps, but I set up my autocomplete a bit differently. I use the source property which allows me to control the call back to jQuery. My ajax call returns items in the form of [{"id":1, "label": "Annie Hall",.....]. You could modify the results of the Ajax call however you want depending on how the data comes back from the server. Here is the code I use to call it.

        $("#movieSearch").autocomplete({
            source: function(req, res){
                $.getJSON(
                    "search.aspx",
                    {term : req.term},
                    function(data){
                        res(data);//you can also modify your results before you call res()
                    }
                );
            }
);

One thing in your example which troubles me is the variable results, which seems to me to be a global variable. And we all know (in the words of Douglas Crockford) that global variable are evil.

哀由 2024-11-14 15:11:10

这是当没有结果时检测的方式

source: function( request, response ) {
    $.getJSON( url, {
        term: extractLast( request.term )
    }, response )
    .error(function() {
        console.log("no results");
    });
},

This is how you detect when there is no result

source: function( request, response ) {
    $.getJSON( url, {
        term: extractLast( request.term )
    }, response )
    .error(function() {
        console.log("no results");
    });
},
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文