jQuery-select2通过ajax请求获取远端数据

select2官网:https://select2.org/

1. 默认发送的查询参数

  • term : The current search term in the search box.
  • q : Contains the same contents as term.
  • _type: A “request type”. Will usually be query, but changes to query_append for paginated requests.
  • page : The current page number to request. Only sent for paginated (infinite scrolling) searches.

2. 自定义查询参数(ajax.data

通过ajax.data来传递自定义的参数:

$('#mySelect2').select2({
  ajax: {
    url: 'https://api.github.com/orgs/select2/repos',
    data: function (params) {
      var query = {
        search: params.term,
        type: 'public'
      }

      // Query parameters will be ?search=[term]&type=public
      return query;
    }
  }
});

3. 把返回参数转换为要求的格式(ajax.processResults

$('#mySelect2').select2({
  ajax: {
    url: '/example/api',
    processResults: function (data) {
      // Tranforms the top-level key of the response object from 'items' to 'results'
      return {
        results: data.items
      };
    }
  }
});

4. 预选中状态

要给ajax请求返回的数据设置“预选中”状态需要create and append a new option

5. 分页:使用"infinite scrolling"模式加载数据

为了实现分页,需要通过覆写ajax.data来传递分页相关的参数,params.page表示需要加载的当前页码。

$('#mySelect2').select2({
  ajax: {
    url: 'https://api.github.com/search/repositories',
    data: function (params) {
      var query = {
        search: params.term,
        page: params.page || 1
      }

      // Query parameters will be ?search=[term]&page=[page]
      return query;
    }
  }
});

在返回结果中需要包括:

"pagination": {
    "more": true
  }

通过more的ture/false来告诉select2是否有更多结果。
如果返回结果中不直接包含more,也可以通过processResults,结合其他信息进一步计算出more的值,比如说返回了总数据量和当前页码的情况下:

processResults: function (data, params) {
    params.page = params.page || 1;

    return {
        results: data.results,
        pagination: {
            more: (params.page * 10) < data.count_filtered
        }
    };
}

6. 延时发送请求

$('#mySelect2').select2({
  ajax: {
    delay: 250 // wait 250 milliseconds before triggering the request
  }
});

7. 动态url

如果请求的url不是固定的,或者需要通过一个方法来判断到底请求哪个url:

$('#mySelect2').select2({
  ajax: {
    url: function (params) {
      return '/some/url/' + params.term;
    }
  }
});

8. 自定义ajax请求方法

默认的ajax请求是通过jquery的ajax请求发出的,也可以通过覆写ajax.transport来通过自定义方法发送。

9. 综合实例

通过github的接口来搜索github上面的仓库

$(".js-example-data-ajax").select2({
  ajax: {
    url: "https://api.github.com/search/repositories",
    dataType: 'json',
    delay: 250,
    data: function (params) {
      return {
        q: params.term, // search term
        page: params.page
      };
    },
    processResults: function (data, params) {
      // parse the results into the format expected by Select2
      // since we are using custom formatting functions we do not need to
      // alter the remote JSON data, except to indicate that infinite
      // scrolling can be used
      params.page = params.page || 1;

      return {
        results: data.items,
        pagination: {
          more: (params.page * 30) < data.total_count
        }
      };
    },
    cache: true
  },
  placeholder: 'Search for a repository',
  escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  minimumInputLength: 1,
  templateResult: formatRepo,
  templateSelection: formatRepoSelection
});

function formatRepo (repo) {
  if (repo.loading) {
    return repo.text;
  }

  var markup = "<div class='select2-result-repository clearfix'>" +
    "<div class='select2-result-repository__avatar'><img src='" + repo.owner.avatar_url + "' /></div>" +
    "<div class='select2-result-repository__meta'>" +
      "<div class='select2-result-repository__title'>" + repo.full_name + "</div>";

  if (repo.description) {
    markup += "<div class='select2-result-repository__description'>" + repo.description + "</div>";
  }

  markup += "<div class='select2-result-repository__statistics'>" +
    "<div class='select2-result-repository__forks'><i class='fa fa-flash'></i> " + repo.forks_count + " Forks</div>" +
    "<div class='select2-result-repository__stargazers'><i class='fa fa-star'></i> " + repo.stargazers_count + " Stars</div>" +
    "<div class='select2-result-repository__watchers'><i class='fa fa-eye'></i> " + repo.watchers_count + " Watchers</div>" +
  "</div>" +
  "</div></div>";

  return markup;
}

function formatRepoSelection (repo) {
  return repo.full_name || repo.text;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值