使用另一个AJAX请求过滤Select2插件中的AJAX响应

时间:2017-01-09 12:49:23

标签: jquery ajax jquery-select2

我是JS的新手,在我的新项目中得到了select2,目前我有这样的代码(这是一个简化版本),效果很好:

  $("#group-search").select2({
    ajax: {
      url: "groups.search",
      dataType: 'jsonp',
      data: function (term, page) {
        return {
          q: term,
          access_token: access_token
        };
      },
      results: function (data, page) {
        return { results: data.response.items };
      }
    }
  });

但我需要在另一个AJAX请求的帮助下过滤我的结果(data.response.items)。有可能以某种方式实现吗?

更新1

这是我根据ValLenain尝试做的事情  提案,但它不起作用:

  results: function (data, page) {
    var groups = data.response.items;

    var groupIds = new Array;
    groups.forEach( function (group) {
      groupIds.push(group.id);
    });

    $.ajax({
      url: "groups.getById",
      dataType: 'jsonp',
      data: {
        group_ids: groupIds,
        v: '5.60',
        access_token: access_token
      },
      success: function(data, page) {
        return { results: data.response };
      }
    }).then(function(response){
      groups = []; 
// so at this moment we are expecting the select field to become empty, right?
// it doesn't work that way, nothing changes
    });

    return { results: groups };
  }

1 个答案:

答案 0 :(得分:0)

我从未尝试过,但是如果您首先返回一个空数组并在ajax调用中更新它,那么使用ajax调用更改<td>函数可能会有效。

results

关于您的更新1

您正在更改results: function (data, page) { var items = []; /* Since I don't know what your ajax call is nor * what it takes as arguments or returns, I just write * a fake one. */ ajaxCall(data.response.items).then(function(filteredItems) { /* update here the items array * it's important to change the existing object, not * to create a new one */ }); return { results:items }; } 变量引用的对象,因此,之前返回的内容(groups)将不会更新。

我重写了函数的主体

data.response.items