【问题标题】:How to send query parameters through $.post method?如何通过 $.post 方法发送查询参数?
【发布时间】:2019-12-09 16:41:53
【问题描述】:

我有一个问题,如何将我的 JSON 字符串发送到 $.post 调用。由于 $.post 默认 ContentType 是 application/x-www-form-urlencoded 但我的服务器只接受 application/json 标头

我在 $.post 通话中需要帮助的原因是我想要快速的结果

这是我的示例代码供参考:

var jqxhr = $.post(url, sendData, function(data) {

    console.log(data);
  })
  .done(function() {

  })
  .fail(function(data) {
    console.log("Failed");
    console.log(data);
  })
  .always(function() {

  });

// Perform other work here ...

// Set another completion function for the request above
jqxhr.always(function() {

});

var obj = {
  "timeout": "5s",
  "_source": false,
  "query": {
    "nested": {
      "path": "demo",
      "query": {
        "multi_match": {
          "query": request,
          "type": "phrase",
          "operator": "and",
          "fields": ["name"]
        }
      },
      "inner_hits": {

        "highlight": {
          "fields": {
            "name": {},
          }
        }
      }
    }
  }
};

var sendData = JSON.stringify(obj);

【问题讨论】:

  • 包含在网址中
  • 检查我的参数
  • 不工作兄弟:(
  • 只需将obj 作为第二个参数传递或尝试使用$.ajax

标签: jquery api http-headers .post


【解决方案1】:

$.post 是一个简写的 Ajax 函数

你可以直接使用$.ajax()

$.ajax({
  url: url,
  type: 'post',
  dataType: 'json',
  contentType: 'application/json',
  data: sendData  // JSON string
});

使用$.ajaxSetup()

为未来的 Ajax 请求设置默认值。它的用途不是 推荐。

$.ajaxSetup({
  contentType: 'application/json',
});

$.post(url, sendData, function(data) {

});

注意: jqXHR.success()jqXHR.error()jqXHR.complete() 回调在 jQuery 1.8 中是 deprecated

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-11
    • 1970-01-01
    • 2015-07-03
    • 1970-01-01
    • 2014-03-30
    相关资源
    最近更新 更多