我注意到,在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?


当前回答

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

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

其他回答

我有类似的问题与以下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

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

美元。如果你有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) {...}
});

我想你可能不得不这么做

1.将源代码修改为$。post总是使用JSON数据类型,因为它实际上只是一个预配置的$的快捷方式。ajax调用

Or

2.定义您自己的实用函数,它是$。您想使用的Ajax配置

Or

3.你可以覆盖$。通过monkey补丁,发布你自己的实现功能。

示例中的JSON数据类型是指从服务器返回的数据类型,而不是发送到服务器的格式。

问题的核心是,在编写本文时,JQuery还没有postJSON方法,而getJSON存在并做正确的事情。

postJSON方法会做以下事情:

postJSON = function(url,data){
    return $.ajax({url:url,data:JSON.stringify(data),type:'POST', contentType:'application/json'});
};

并且可以这样使用:

postJSON( 'path/to/server', my_JS_Object_or_Array )
    .done(function (data) {
        //do something useful with server returned data
        console.log(data);
    })
    .fail(function (response, status) {
        //handle error response
    })
    .always(function(){  
      //do something useful in either case
      //like remove the spinner
    });

我们可以在$.post中像这样更改Content-type

$.post(url,data, function (data, status, xhr) {
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");});