【问题标题】:How to get data of select2 with POST method如何使用 POST 方法获取 select2 的数据
【发布时间】:2021-07-06 10:42:22
【问题描述】:

我需要用 POST 方法返回 select2 的数据。 有谁知道我能做什么? 我试过这个,但甚至没有工作。

$("#action").select2({
  allowHtml: true,
  ajax: {
    type: "POST",
    url: URL,
    headers: {
      "Content-Type": "application/json",
      Authorization: "Bearer " + localStorage.getItem("api_token")
    },
    dataType: "json",
    data: function(term, page) {
      console.log(term);
      return {
        string: term
      };
    },
    processResults: function(data) {
      console.log(data);
      return {
        results: data.map(item => {
          return {
            text: item.title,
            id: item.id
          };
        })
      };
    }
  },
  allowClear: !0
});
<input class="form-control" id="action">

代码甚至不显示日志。

【问题讨论】:

  • 要调试 AJAX 请求,请使用 devtools 的网络选项卡。您将在那里看到请求,以及它的 statusCode 和 responseText。他们应该给你足够的信息来开始调试
  • 它甚至不调用网络中的ajax方法@RoryMcCrossan
  • 控制台有错误吗?
  • @RoryMcCrossan 不,没什么!

标签: javascript jquery jquery-select2


【解决方案1】:

问题是我添加了输入而不是选择标签 我解决了这样的问题

$("#action").select2({
  allowHtml: true,
  ajax: {
    type: "POST",
    url: URL,
    headers: {
      "Content-Type": "application/json",
      Authorization: "Bearer " + localStorage.getItem("api_token")
    },
    dataType: "json",
    data: function(term, page) {
      console.log(term);
      return {
        string: term
      };
    },
    processResults: function(data) {
      console.log(data);
      return {
        results: data.map(item => {
          return {
            text: item.title,
            id: item.id
          };
        })
      };
    }
  },
  allowClear: !0
});
<select class="form-control" id="action"></select>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-02
    • 1970-01-01
    • 1970-01-01
    • 2019-05-22
    • 2016-01-31
    • 1970-01-01
    • 2017-02-24
    • 2013-05-21
    相关资源
    最近更新 更多