简体   繁体   English

在后台加载Ajax select2数据页面

[英]Loading pages of ajax select2 data in the background

I have a AJAX select2 drop-down menu set up to do infinite paging. 我设置了一个AJAX select2下拉菜单来进行无限分页。 What'd I'd like to do is go ahead and load the first page of results in the background so that as soon as the user clicks the drop-down, they have a set of options immediately, instead of waiting on the initial AJAX call. 我想做的是继续进行,并将结果的第一页加载到后台,以便用户单击下拉列表后,他们会立即具有一组选项,而不必等待初始的AJAX呼叫。

When I search Google for how to do this, I only see results about trying to set an initial selection, which isn't what I want to do. 当我搜索Google的操作方法时,只会看到尝试设置初始选择的结果,这不是我想要的。 I just want to pre-load the first page of results from my endpoint so the user sees data immediately instead on waiting for the AJAX call to return. 我只想从端点预加载结果的第一页,以便用户立即查看数据,而不必等待AJAX​​调用返回。 Is this even possible? 这有可能吗?

My select2 setup code is below: 我的select2设置代码如下:

$(".my-class-identifier").select2({

        ajax: {
            cache: true,
            dataType: "json",
            delay: 500, 
            data: function(params, page) {

                return {
                    name: params,
                    otherParams: $(this).data("other-params")
                    page: page                      
                };

            },
            results: function(data, page) {

                return {
                    /* The server returns no data after all the pages have been returned. */
                    more: data && data.length > 0,
                    results: data
                };

            },
            type: "GET",
            url: function() {
                if ($(this).data("url")) {
                    return $(this).data("url");
                } else {
                    return DEFAULT_ENDPOINT;
                }
            }
        },
        allowClear: true,
        minimumInputLength: 0,
        placeholder: "Search for some data..."          
    });

So what you are looking for is to initialize your select2. 因此,您要寻找的是初始化select2。 Select2 has an initialize option to load your values, it would look something like this: Select2有一个初始化选项来加载您的值,它看起来像这样:

    initSelection: function(element, callback){
        callback([
           {id:1,text:'one'},
           {id:2,text:'two'},
        ]);
    }

Be sure to add this outside your ajax call, but inside your select2. 确保将其添加到您的ajax调用之外,但在您的select2内部。

An example here in JSFiddle JSFiddle中的一个示例

How about in your backend, you check your search string. 怎么样,在后端,您检查您的搜索字符串。 If the size is zero or the search string is empty, then send back your first-page result. 如果大小为零或搜索字符串为空,则发送回首页结果。 Otherwise, do the search and return the result. 否则,进行搜索并返回结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM