我有一个问题,在初始化Select2(其中一个url属性设置在ajax帮助器中)和ajax调用的时间之间,此url可能需要更改.
所以我有这样的东西:
- $Box.select2({
- containerCssClass: "form-control"
- minimumInputLength: 0,allowClear: true,ajax: {
- url: someUrl,dataType: 'json',quietMillis: 100,...
- }
在启动之前,我不知道如何,何时更改ajax.url值.
Select2的帮助说:
Select2 uses jQuery’s
$.ajax
function to execute the remote call by default. An alternativetransport
function can be specified in theajax
settings,or an entirely custom implementation can be built by providing a customquery
function instead of using the ajax helper.
但是我找不到有关如何做的例子.
提前感谢任何帮助.非常感激.
解决方法
I can’t figure out how,when,where to change the ajax.url value before it launches.
ajax.url选项可以指定为静态字符串或在Select2 3.5.x和4.0.0中返回的方法.
- $("select").select2({
- ajax: {
- url: function () {
- return UrlHelper.RemoteAPI();
- }
- }
- });
这对于更改基本URL很有用,例如在运行时确定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 uses jQuery’s $.ajax function to execute the remote call by default. An alternative transport function can be specified in the ajax settings,or an entirely custom implementation can be built by providing a custom query function instead of using the ajax helper.
但是我找不到有关如何做的例子.Select2允许通过更改ajax.transport选项来使用不同的AJAX传输.
在3.5.2中,这必须是一个$.ajax兼容的方法,所以它必须能够获取包含成功和失败回调的对象.
- $("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),成功回调和失败回调的方法.
- $("select").select2({
- ajax: {
- transport: function (params,success,failure) {
- var $request = $.ajax(params);
- $request.then(success);
- $request.fail(failure);
- return $request;
- }
- }
- });