微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

jquery-select2 – Select2在调用时使用动态Ajax URL

我使用带有Ajax的Select2插件(v 3.5.2)来动态地加载列表中的元素.

我有一个问题,在初始化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 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.

但是我找不到有关如何做的例子.

提前感谢任何帮助.非常感激.

解决方法

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;
    }
  }
});

原文地址:https://www.jb51.cc/jquery/176047.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐