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


当前回答

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

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

其他回答

你不能直接发送application/json——它必须是GET/POST请求的参数。

就像这样

$.post(url, {json: "...json..."}, function());

我最终在我的脚本中添加了以下方法:

jQuery["postJSON"] = function( url, data, callback ) {
    // shift arguments if data argument was omitted
    if ( jQuery.isFunction( data ) ) {
        callback = data;
        data = undefined;
    }

    return jQuery.ajax({
        url: url,
        type: "POST",
        contentType:"application/json; charset=utf-8",
        dataType: "json",
        data: data,
        success: callback
    });
};

然后使用它

$.postJSON('http://url', {data: 'goes', here: 'yey'}, function (data, status, xhr) {
    alert('Nailed it!')
});

这是通过简单地从原始JQuery源代码中复制“get”和“post”的代码并硬编码一些参数来强制JSON post来实现的。

谢谢!

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

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

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

我想你可能不得不这么做

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

Or

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

Or

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

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