从ajax设置json数据,并使其在select2 jQuery中可搜索 [英] set json data from ajax and make it serarchable in select2 jQuery

查看:286
本文介绍了从ajax设置json数据,并使其在select2 jQuery中可搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个下拉输入字段,都在实现Select2 Jquery.在这里,我首先将数据设置为静态.它的工作很好.根据第一个下拉列表中的值选择,下一个下拉列表将由ajax填充另一组json数据.我需要第二个下拉列表应该仅在加载ajax数据后才可搜索.但我不正确.我无法使其可行.

I had two drop down input fields, both are implementing Select2 Jquery. Here i set the data as static for first drop down . its works fine . As per selection of value in first drop down, next drop down will filled by another set of json data by ajax. I need to second drop down should be searchable with only once loaded the ajax data. but i am not get correctly. i not able to make it workable.

我使用了以下脚本

function format(item) { return item.name; }
        var data=[{"id":"1995","name":"Banahatti"},{"id":"5074","name":"Kolhapur(Maharashtra)"},{"id":"2356","name":"Sangola"},{"id":"906","name":"Shahada"}];    
$("#txtSource").select2({
                data:function() { return { text:'name', results: data }; },
                formatSelection: format,
                formatResult: format
            });

第二个下拉菜单加载如下

for second drop down loaded like following

        var theID,desdata;
        $("#txtSource").on('change',function(){
           theID = $("#txtSource").select2('data').id;
           desdata= $.getJSON('api/destination.php',{source:theID});
            //console.log(desdata);
            });

        $("#txtDestination").select2({
            data:function() { return { text:'name', results:desdata  }; },
            formatSelection: format,
            formatResult: format
         });

推荐答案

您必须更改data()函数.它应尝试在创建用于存储select2结果的变量(应为{obj.firstSelectKey:{results:data []}之类的对象)中查找已经下载或硬编码的数据.如果特定键下没有数据,则应该执行ajax请求.

You have to change the data() function. It should try to find already downloaded or hardcoded data in a variable (should be an Object like {obj.firstSelectKey: {results: data[]}) created to store select2 results. If there is no data under a specific key, an ajax request should be done.

还为jQuery ajax/select2 ajax请求提供了缓存参数,但是该参数由浏览器处理,因此您不必决定是否应存储ajax数据,但浏览器可以.浏览器xhr缓存不受控制.

Also there is cache parameter for jQuery ajax/select2 ajax requests, but it is handled by browser so not you decide if ajax data should be stored but the browser does. There is no control on browser xhr cache.

这篇关于从ajax设置json数据,并使其在select2 jQuery中可搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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