我注意到,在jquery中使用$.post()时,默认的内容类型是application/x-www-form-urlencoded -当我的asp.net mvc代码需要有contentType=application/json

(请参阅这个问题,为什么我必须使用application/json: ASPNET MVC -为什么是ModelState。当该字段有值时,该x字段是必需的?)

我怎么能让$.post()发送contentType=应用程序/json?我已经有了大量的$.post()函数,所以我不想更改为$.ajax(),因为这会花费太多时间

如果我尝试

$.post(url, data, function(), "json") 

它仍然有contentType=application/x-www-form-urlencoded。那么,如果“json”参数没有将内容类型更改为json,它究竟做了什么呢?

如果我尝试

$.ajaxSetup({
  contentType: "application/json; charset=utf-8"
});

这是可行的,但影响到每一美元。Get和$。帖子,我有和导致一些打破。

那么是否有一些方法,我可以改变$.post()的行为发送contentType=application/json?


当前回答

美元。如果你有CORS(跨源资源共享)问题,post将无法工作。尝试使用$。Ajax的以下格式:

$.ajax({
        url: someurl,
        contentType: 'application/json',
        data: requestInJSONFormat,
        headers: { 'Access-Control-Allow-Origin': '*' },
        dataType: 'json',
        type: 'POST',
        async: false,
        success: function (Data) {...}
});

其他回答

最后我找到了适合我的解决方案:

jQuery.ajax ({
    url: myurl,
    type: "POST",
    data: JSON.stringify({data:"test"}),
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function(){
        //
    }
});

美元。如果你有CORS(跨源资源共享)问题,post将无法工作。尝试使用$。Ajax的以下格式:

$.ajax({
        url: someurl,
        contentType: 'application/json',
        data: requestInJSONFormat,
        headers: { 'Access-Control-Allow-Origin': '*' },
        dataType: 'json',
        type: 'POST',
        async: false,
        success: function (Data) {...}
});

你猜怎么着?@BenCreasy完全正确!!

从jQuery 1.12.0版本开始,我们可以这样做:

$.post({
    url: yourURL,
    data: yourData,
    contentType: 'application/json; charset=utf-8'
})
    .done(function (response) {
        //Do something on success response...
    });

我刚刚测试了一下,它工作了!!

我有类似的问题与以下JavaScript代码:

var url = 'http://my-host-name.com/api/Rating';

var rating = { 
  value: 5,
  maxValue: 10
};

$.post(url, JSON.stringify(rating), showSavedNotification);

在Fiddler中,我可以看到请求:

标题:Content-Type: application/x-www-form-urlencoded;utf - 8字符集= 身体:{“价值”:“5”,“执行”:“5”}

因此,我的服务器无法将对象映射到服务器端类型。

把最后一行改成这样:

$.post(url, rating, showSavedNotification);

在《提琴手》里我还能看到:

标题:Content-Type: application/x-www-form-urlencoded;utf - 8字符集= 身体:价值= 5 maxvalue = 10

然而,服务器开始返回我所期望的结果。

出于某种原因,在ajax请求上设置@Adrien建议的内容类型在我的情况下不起作用。但是,您实际上可以使用$更改内容类型。在发布之前这样做:

$.ajaxSetup({
    'beforeSend' : function(xhr) {
        xhr.overrideMimeType('application/json; charset=utf-8');
    },
});

然后赚你的美元。post调用:

$.post(url, data, function(), "json")

我有jQuery + IIS的问题,这是唯一的解决方案,帮助jQuery理解使用windows-1252编码ajax请求。