将外部json预加载到选择框中,然后在搜索后获取特定结果

所以我期待在select2框中加载外部数据,其中有来自json的预填充结果

我有两个问题 – 获取数据然后只加载前几个但当用户搜索时将请求传递给其余的,然后返回特定的json

所以HTML很简单

 

初始js是

 $(document).ready(function () { $('#e21').select2({ query: function (query){ var data = {results: []}; console.log(data); $.each(preload_data, function(){ if(query.term.length == 0 || this.text.toUpperCase().indexOf(query.term.toUpperCase()) >= 0 ){ data.results.push({id: this.id, text: this.text }); } }); query.callback(data); } }); $('#e21').select2('data', preload_data ); }); 

这样做是在preload_data中加载所以可能

 var preload_data = [ { id: 'user0', text: 'Disabled User'}, { id: 'user1', text: 'Jane Doe'}, { id: 'user2', text: 'John Doe', locked: true }, { id: 'user3', text: 'Robert Paulson', locked: true }, { id: 'user5', text: 'Spongebob Squarepants'}, { id: 'user6', text: 'Planet Bob' }, { id: 'user7', text: 'Inigo Montoya' } ]; 

一个例子就在这里

http://jsfiddle.net/dwhitmarsh/MfJ4B/10/

但我没有在preload_data中加载ajax调用中的加载并传递结果

所以我可以使用

 var preload_data = $.ajax({ url: 'data/more.json', method: 'get', dataType: 'json' }); 

但是需要等待json加载并且只想在前10个加载。

然后,当用户实际搜索时,我想传递额外的变量,如

 string: term, //search term page_limit: 10, // page size page: page // page number 

页面是选择2的一部分

有人可以帮忙吗?

顺便说一下,more.json看起来像

 { "total": 8, "result": [{ "id": "1", "label": "Type", "safeName":"type", "jsonFile": "type.json" },{ "id": "2", "label": "Primary Applicant Name", "safeName":"primaryApplicantName", "jsonFile": "primary.json" },{ "id": "3", "label": "Address", "safeName":"address", "jsonFile": "address.json" },{ "id": "4", "label": "Product", "safeName":"product", "jsonFile": "product.json" },{ "id": "5", "label": "Verification", "safeName": "verification", "jsonFile": "verification.json" },{ "id": "6", "label": "Documents", "safeName": "documents", "jsonFile": "documents.json" },{ "id": "7", "label": "Suburb", "safeName": "suburb", "jsonFile": "suburb.json" },{ "id": "8", "label": "State", "safeName": "state", "jsonFile": "state.json" }] }