Jquery 使用另一个AJAX请求过滤Select2插件中的AJAX响应
我是JS新手,在我的新项目中得到了select2,目前我有这样的代码(这是一个稍微简化的版本),它工作得很好:Jquery 使用另一个AJAX请求过滤Select2插件中的AJAX响应,jquery,ajax,jquery-select2,Jquery,Ajax,Jquery Select2,我是JS新手,在我的新项目中得到了select2,目前我有这样的代码(这是一个稍微简化的版本),它工作得很好: $("#group-search").select2({ ajax: { url: "groups.search", dataType: 'jsonp', data: function (term, page) { return { q: term, access_token: ac
$("#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
这就是我一直试图做的
建议,但它不起作用:
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 };
}
我从未尝试过,但是如果您首先返回一个空数组并在ajax调用中更新它,那么使用ajax调用更改
结果
函数可能会起作用
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 };
}
关于您的更新1
您正在更改groups
变量所引用的对象,因此之前返回的(data.response.items
)将不会更新
我已经重写了函数的主体
/* Set groups to an empty array so the select2
* component will never display unfiltered value.
*/
var groups = [];
var groupIds = new Array;
data.response.items.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) {
/* Here I assume your items are in data.response.items.
* We push all the items into the existing array, without
* creating a new array (so we keep the reference).
*/
Array.prototype.push.apply(groups, data.response.items);
/* The return statement is optional here */
return { results: data.response };
}
});
return {
results: groups
}
@VaIleNain,但是
不会返回{results:items}在函数(filteredItems)
之前长时间激发code>语句?这不是AJAX调用的重点吗?还是我在这里漏掉了什么?@VaILeNain,我刚刚试过,效果如我所料<代码>返回{results:items}代码>在过滤ajax调用之前触发。如果您需要完整的代码,我可以更新我的main postyes,return语句将在第二个ajax调用之前很久执行,但是它返回的对象(例如,{results:items}
)将在ajax调用之后更新,因为我们保留了对它的引用。@VaILeNain,我明白了。但是这个物体现在已经被归还了,对吗?那么,如果它已经返回,并且选择字段已经填充了初始(未过滤)数据,那么它将被更新会有什么区别呢?我试过你的想法,但没有任何改变。查看我的更新答案。您的更新也不起作用。它显示空结果。我不知道该给你提供什么信息。目前,我找到了另一个js插件(selectize.js),我使用$.when($.ajax({…})。然后(function(content){$.ajax({…}))解决了我的问题。
。