【问题标题】:Posting JSON using JQuery and to set HTTP content type - 'application /json'使用 JQuery 发布 JSON 并设置 HTTP 内容类型 - 'application /json'
【发布时间】:2014-01-17 18:18:53
【问题描述】:

我正在使用 jquery 将 Json 数据发布到服务器。但是,当我发出如下发布请求时,

    $.ajax({
                type        :   'POST'  ,
                url         :   uri,
                data        :   jsonStrJson,
                contentType :   'application/json',
                success     :   successFunction
        });

即使我发布了一个 json 对象,http 请求标头内容类型也不是“application/json”。

由于不是applcation/json,服务器不处理requset,返回415。

有没有办法使用 javascript 或 jquery API 设置标头?

【问题讨论】:

  • contentTYpe -> contentType ?
  • 非常敏锐的眼睛@JasonP,我错过了它
  • 欣赏它。非常感谢我发布了这个想法,我不了解 AJAX 的 Jquery API。我的错。谢谢杰森

标签: ajax json jquery http-post


【解决方案1】:

你可以试试这个,

$.ajax({
    beforeSend: function(xhrObj){
        xhrObj.setRequestHeader("Content-Type","application/json");
        xhrObj.setRequestHeader("Accept","application/json");
    },
    type: "POST",
    url: uri,       
    data: jsonStrJson,               
    dataType: "json",
    success: function(json){
       console.log(json);
    }
});

【讨论】:

    【解决方案2】:

    “contentType”而不是“contentType”也应该可以解决问题。 ;)

    【讨论】:

      【解决方案3】:

      对于设置http请求头参数也可以试试这个方法:

      $.ajax({
             type        :   'POST'  ,
             url         :   uri,
             data        :   jsonStrJson,
             headers     : { 'Content-Type': 'application/json' }, //this line
             success     :   successFunction
              });
      

      【讨论】:

        猜你喜欢
        • 2014-04-26
        • 2017-07-06
        • 2012-02-28
        • 2015-10-09
        • 1970-01-01
        • 2014-01-06
        • 1970-01-01
        • 1970-01-01
        • 2017-04-27
        相关资源
        最近更新 更多