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

时间:2013-06-07 07:33:09

标签: ajax json jquery jquery-select2

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

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

因此HTML很简单

<input type="hidden" id="e21" style="width:300px;"/> 

初始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/

但是我想在ajax调用中加载并传递结果而不是preload_data

所以我可以使用

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

页面是select 2

的一部分

任何人都可以帮忙吗?

btw 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"


    }]
}

0 个答案:

没有答案