我不知道在启动之前如何、何时、在何处更改 ajax.url 值。
ajax.url 选项可以指定为静态字符串或在 Select2 3.5.x 和 4.0.0 中返回一个的方法。
$("select").select2({
ajax: {
url: function () {
return UrlHelper.RemoteAPI();
}
}
});
这对于更改 基本 URL 很有用,例如当 URL 在运行时确定或以不同的方法自动生成时。如果您需要更改查询参数,例如用于发送搜索词的参数,则需要覆盖ajax.data 选项。
$("select").select2({
ajax: {
data: function (args) {
// args is the search term in 3.5.x
// args is an object containing the query parameters in 4.0.0
// args.term is the search term in 4.0.0
return {
search: args.term || args;
};
}
}
});
这里的数据默认作为查询参数附加,如果方法类型从GET(默认)更改为其他任何内容,将作为请求正文发送。
Select2 默认使用 jQuery 的 $.ajax 函数来执行远程调用。可以在 ajax 设置中指定替代传输函数,或者可以通过提供自定义查询函数而不是使用 ajax 帮助器来构建完全自定义的实现。
但我找不到任何关于如何做到这一点的示例。
Select2 确实允许通过更改 ajax.transport 选项来使用不同的 AJAX 传输。
在 3.5.2 中,这必须是与 $.ajax 兼容的方法,因此它必须能够获取包含 success 和 failure 回调的对象。
$("select").select2({
ajax: {
transport: function (args) {
// args.success is a callback
// args.failure is a callback
// should return an object which has an `abort` method.
return $.ajax(args);
}
}
});
在 4.0.0 中,这必须是一个接受 params 对象(与传递给 ajax.data 的对象相同)、success 回调和 failure 回调的方法。
$("select").select2({
ajax: {
transport: function (params, success, failure) {
var $request = $.ajax(params);
$request.then(success);
$request.fail(failure);
return $request;
}
}
});