如何使用带有 AJAX JSON 数据的 jQuery 自动完成组合框? [英] How to use a jQuery autocomplete combobox with AJAX JSON data?

查看:21
本文介绍了如何使用带有 AJAX JSON 数据的 jQuery 自动完成组合框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用组合框执行以下操作.

I need to do the following using a combobox.

  • 选择框有一个默认的城市列表,用户可以从中搜索.
  • 如果用户在 input 框中输入文本,我需要进行 ajax 调用以获取数据并向用户显示选项.
  • 如果为用户请求获取数据,则应将这些城市附加到选择框
  • 的选项中
  • Select box has a default list of cities which the user can search from.
  • If a user types in text in the input box, I need to make an ajax call to fetch data and display the options to the user.
  • If data was fetched for user's request, those cities should be appended to the options of Select box

使用 jQuery 自动完成 我能够在用户输入字符串并显示时获取 json 数据结果.但是,我对如何使用组合框集成此功能一无所知.

Using jQuery autocomplete I am able to fetch json data on user entering a string and displaying the results. However, I am quite clueless on how to integrate this using combobox.

Combobox 使用静态数据数组进行搜索,如果我理解正确,则使用正则表达式来匹配值.但是,如何中断它并使用 ajax 调用从服务器获取数据并更新结果?

Combobox uses a static data array to search from and if I understand this correctly, uses regular expression to match values. However, how do I interrupt it and uses the ajax call to fetch data from server and update the results ?

输入文本框的自动完成:

Autocomplete for input text box:

$( "#searchDestination" ).autocomplete({
        delay: 500,
        source: function( request, response ) {
            $.ajax({
                url: "/wah/destinationsJson.action",
                dataType: "json",
                data: {
                    term: request.term
                },
                type: "POST",
                success: function(data){
                    if(data.cities.length == 0)
                        return response(["No matching cities found for " + request.term]);
                    response( $.map(data.cities, function(item){
                        return{
                            label: item.name,
                            value: item.name
                        };
                    })
                    );
                }
            });
        },
        minLength: 2

    });
    });

推荐答案

这可能对您有所帮助.. 我使用的另一个自动完成插件.

This may help you.. another autocomplete plugin which I used.

另请阅读这个

如果您想在文本字段中动态加载数据,请使用上述插件.否则,如果你想使用组合框,那么只需在 ready() 上加载数据并使用 jquery 自动完成插件!

If you want to load data dynamically in text field, go with above plugin. Else if you want to go with combo box, then just load the data on ready() and use jquery auto complete plugin!

这篇关于如何使用带有 AJAX JSON 数据的 jQuery 自动完成组合框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆