使用 JQuery 发布 JSON 并设置 HTTP 内容类型 - 'application /json'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21193038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 01:28:37  来源:igfitidea点击:

Posting JSON using JQuery and to set HTTP content type - 'application /json'

ajaxjsonjqueryhttp-post

提问by linux developer

I am using jquery to post Json data to server. However when I make a post request as below,

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

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

The http request header content type is not "application/json" even though I posting a json object.

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

Since it is not applcation/json, the server does not process the requset and returns 415.

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

Is there a way to set the header using javascript or jquery API?

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

回答by Krish R

Can you try this,

你可以试试这个吗

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

回答by andreas

"contentType" instead "contentTYpe" should also solve the problem. ;)

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

回答by Hossein Narimani Rad

Also for setting http request header parameters you can try this approach:

同样对于设置 http 请求标头参数,您可以尝试这种方法:

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