$ .post()不会以json的形式发送数据,而是以x-www-form-urlencoded的形式发送数据

byt*_*ave 32 jquery post jquery-post

这个真的很奇怪.我$.post()在代码中有多个,但有一个dunno为什么发送json参数x-www-form-urlencoded而不是因此不起作用.

这是代码:

$.post("/Route/SaveTransportProperties", { properties: JSON.stringify(propArray), currTravelBox: JSON.stringify(travelBoxObj), accessToken: getAccessToken()}, function(data)
    {
        //DO STUFF
    });
Run Code Online (Sandbox Code Playgroud)

XHR在Firefox中看起来像这样: Firefox截图

任何想法为什么会发生这种情况?我还将类型强制为'json',但也不起作用.

Jam*_*urz 39

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

您可以指定type post和dataType 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
  },
});
Run Code Online (Sandbox Code Playgroud)

取自ajax文档

http://api.jquery.com/jQuery.ajax/

contentTypeString
Default: 'application/x-www-form-urlencoded; charset=UTF-8'
Run Code Online (Sandbox Code Playgroud)

  • dataType指定_response_的预期类型,而不是post数据.Olli的答案是正确的 - 您需要使用$ .ajax并指定contentType选项. (2认同)

Oll*_*lli 8

因为$ .post()用于发送类似表单的请求.$ .ajax用于发送您想要的任何内容.请参见contentType$.ajax页面了解更多信息.

引用:

将数据发送到服务器时,请使用此内容类型.默认为"application/x-www-form-urlencoded",这对大多数情况都适用.如果您明确地将内容类型传递给$ .ajax(),那么它将始终发送到服务器(即使没有数据发送).数据将始终使用UTF-8字符集传输到服务器; 你必须在服务器端适当地解码它.


moh*_*ari 5

这也适用于我

$.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
  },
});
Run Code Online (Sandbox Code Playgroud)