简体   繁体   中英

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

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 ie 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"
      }
   ]
}

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
                }
            }),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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