Jquery $.post()不';t以json格式发送数据,而以x-www-form-urlencoded格式发送数据

Jquery $.post()不';t以json格式发送数据,而以x-www-form-urlencoded格式发送数据,jquery,post,Jquery,Post,这个真的很奇怪。我在代码中有多个$.post(),但有一个不知道为什么会将json参数改为x-www-form-urlencoded,因此不起作用 代码如下: $.post("/Route/SaveTransportProperties", { properties: JSON.stringify(propArray), currTravelBox: JSON.stringify(travelBoxObj), accessToken: getAccessToken()}, f

这个真的很奇怪。我在代码中有多个
$.post()
,但有一个不知道为什么会将json参数改为
x-www-form-urlencoded
,因此不起作用

代码如下:

$.post("/Route/SaveTransportProperties", { properties: JSON.stringify(propArray), currTravelBox: JSON.stringify(travelBoxObj), accessToken: getAccessToken()}, function(data)
    {
        //DO STUFF
    });
XHR在Firefox中看起来像这样:


你知道为什么会这样吗?我还将该类型强制为“json”,但也不起作用。

如果要将数据作为json发送,请使用$.ajax函数

您可以指定类型post和数据类型json

$.ajax({
  url: "mydomain.com/url",
  type: "POST",
  dataType: "xml/html/script/json", // expected format for response
  contentType: "application/json", // send as JSON
  data: $.param( $("Element or Expression") ),

  complete: function() {
    //called when complete
  },

  success: function() {
    //called when successful
 },

  error: function() {
    //called when there is an error
  },
});
摘自ajax文档

因为它是用来发送表单式请求的。是用来发送你想要的任何东西的。有关更多信息,请参见
$.ajax
页面中的
contentType

引述:

向服务器发送数据时,请使用此内容类型。默认值为“application/x-www-form-urlencoded”,这在大多数情况下都适用。如果显式地将内容类型传递给$.ajax(),则它将始终发送到服务器(即使没有发送数据)。数据将始终使用UTF-8字符集传输到服务器;您必须在服务器端对其进行适当解码


您还可以在success函数中强制数据为json:
data=JSON.parse(数据)

这也适用于我

$.ajax({
  url: "mydomain.com/url",
  type: "POST",
  dataType: "xml/html/script/json", // expected format for response
  contentType: "application/json", // send as JSON
  data: JSON.stringify(data),

  complete: function() {
    //called when complete
  },

  success: function() {
    //called when successful
 },

  error: function() {
    //called when there is an error
  },
});

Post是$.ajax()的缩写,因此它应该可以工作,而且我在代码中的其他地方也可以使用它。。。。就在这里,它似乎失败了。我不使用$.ajax()的原因是因为在IE9 compat模式下引发了一个异常“SCRIPT87:Invalid Arguments”。但是使用$.post()(除了它不工作之外……我的问题是)不会引发任何错误。好的。我可能是从某个地方,或者可能是从一个旧的或更新的jquery版本错误地复制了ajax代码,但是为什么ajax不起作用(请参见我在Olli answer下的评论)的问题是bc的类型参数中,我使用了“JSON”而不是“POST”数据类型指定了预期的响应类型,而不是POST数据。Olli的回答是正确的-您需要使用$.ajax并指定contentType选项。$.param(obj)可以替换为性能更好的JSON.stringify(obj)。请参见此处的基准:
$.ajax({
  url: "mydomain.com/url",
  type: "POST",
  dataType: "xml/html/script/json", // expected format for response
  contentType: "application/json", // send as JSON
  data: JSON.stringify(data),

  complete: function() {
    //called when complete
  },

  success: function() {
    //called when successful
 },

  error: function() {
    //called when there is an error
  },
});