jQuery.map() to Parse results from select2 ajax call

白昼怎懂夜的黑 提交于 2019-12-12 05:05:24

问题


I have the following select2 ajax call. How do I use the jquery $.map() to parse the returned json results. From the users array i need to get the Text and Value results. From the pager array I need to get the TotalItemCount. What I have below doesnt seem to work i.e the search results don't seem to display in the select list. No console errors are shown either so I'm not sure what Im doing wrong.

var url = '@Url.Action("GetEmployees", "Employees")';
var pageSize = 20;

$(".js-data-example-ajax").select2({
    ajax: {
        url: url,
        dataType: 'json',
        delay: 250,
        data: function (params) {
            return {
                term: params.term, // search term
                page: params.page
            };
        },
        processResults: function (data, params) {
            params.page = params.page || 1;

            return {
                results:  $.map(data, function (users) {
                    return {
                        text: users.Text,
                        id: users.Value
                    }
                }),
               pagination: {
                    more: (params.page * pageSize) < data.pager.TotalItemCount
                }
            };
        },
        cache: true
    },
    minimumInputLength: 2,
    placeholder: "-- Select --",
    allowClear: true
});

The json returned is as follows:

 {
   "pager":{
      "PageCount":1,
      "TotalItemCount":1,
      "PageNumber":1,
      "PageSize":20,
      "HasPreviousPage":false,
      "HasNextPage":false,
      "IsFirstPage":true,
      "IsLastPage":true,
      "FirstItemOnPage":1,
      "LastItemOnPage":1
   },
   "users":[
      {
         "Disabled":false,
         "Group":null,
         "Selected":false,
         "Text":"Joe Blogs",
         "Value":"97306aa4-d423-4770-9b45-87a701146b10"
      }
   ]
}

回答1:


I was correct. I wasn't using the jQuery.map() correctly. It should be as follows:

 results:  $.map(data.users, function (users) {
                return {
                    text: users.Text,
                    id: users.Value
                }
            }),


来源:https://stackoverflow.com/questions/38556750/jquery-map-to-parse-results-from-select2-ajax-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!