weixin_33725270 2016-08-11 01:39 采纳率: 0%
浏览 26

Ajax select2示例

I'm needing to download names of cities in a comboBox Select2 via ajax, but so far it has not worked. many examples in internet search, but not understand them too.

$(document).ready(function() {
    var url = "http://localhost:8000/api/city?";
    $("#city").select2({
        minimumInputLength: 1,
        ajax: {
            url: url,
            dataType: 'json',
            type: "GET",
            delay: 500,
            data: function (term) {
            return {
                city: term
            };
        },
        results: function (data) {
            console.log(data);
            return {
                results: $.map(data, function (item) {
                    return {
                        text: item.text,
                        id: item.id
                    }
                })
            };
        }
    }
});
});

y este es el código json que devuelve mi servidor con la consulta realizada:

[{ "id": 1, "text": "Capital, Córdoba, Argentina" }]

Dice "Searching...." y luego "No results found"

Really, Thanks!

  • 写回答

1条回答 默认 最新

  • larry*wei 2016-08-11 02:10
    关注

    First of all if you are using Select2 version 4+, make sure you initialize select2() on a <select> element or many of his feature like AJAX will be turned off.

    Select2 will need a formated answer from your server at : http://localhost:8000/api/city?

    Response returned by your server should look like this:

    [
        {id:1,text:'city1'},
        {id:2,text:'city2'},
    ]
    

    The options: minimumInputLength = 0, will make it load the whole list on click minimumResultsForSearch , control how many results you need to display the search box into select2 list.

    ajax{data: function(param)} is the function called to format the user data into something your server will understand, what you return here is send to your {ajax:url}

    ajax{processResults: function (data, status)} , this is called when you ajax got a successful response from your server , data will be the response from your server this is the last chance you have to make sure that data is formated like select2 need , see top of this post. What you return here is send to select2.

    Hope it help!

    评论

报告相同问题?

悬赏问题

  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据