jQuery插件select2跨域设置xhrFields参数

时间:2021-07-23 15:06:06

ajax跨越时默认不带cookie,如果需要带cookie调用,需要设置参数 xhrFields: { withCredentials: true },如:

$.ajax({url : "http://www.baidu.com",
dataType :
'json',
xhrFields: { withCredentials:
true },
success:
function(data){console.log(data)}
})

但是在使用jQuery插件select2跨域时,在ajax下直接设参数 xhrFields: { withCredentials: true } 无效,需要在外面包一层params,如下:

$("#s2_input").select2({
placeholder:
"",
ajax: {
url:
"http://www.baidu.com",
params: {
xhrFields: { withCredentials:
true }
},
dataType:
'json',
data:
function (term, page) {
return {
page: page,
count:
25,
q: term
};
},
results:
function (data, page) {
var more = (page * 25) < data.total;
return { results: data.items, more: more };
}
},
formatResult: namesformat,
formatSelection: namesformat,
escapeMarkup:
function (m) { return m; },
initSelection:
function (element, callback) {
var data = [];
$(element.val().split(
",")).each(function () {
data.push({ id:
this, text: this });
});
callback(data);
}
});