$.post() doesn't send data as json but as x-www-form-urlencoded instead

自古美人都是妖i 提交于 2019-11-27 12:46:37

问题


This one is really weird. I've multiple $.post() in the code but there is one dunno why sends the json parameters as x-www-form-urlencoded instead and therefore doesn't work.

Here's the code:

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

The XHR looks like this in Firefox:

Any ideas why is this happening? I also enforced the type as 'json' but doesn't work either.


回答1:


If you want to send the data as json then use the $.ajax function

You can specify type post and 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
  },
});

Taken from ajax documentation

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

contentTypeString
Default: 'application/x-www-form-urlencoded; charset=UTF-8'



回答2:


Because $.post() is for sending form-like requests. $.ajax is for sending whatever you want to. See contentType in $.ajax page for more information.

Quote:

When sending data to the server, use this content-type. Default is "application/x-www-form-urlencoded", which is fine for most cases. If you explicitly pass in a content-type to $.ajax() then it'll always be sent to the server (even if no data is sent). Data will always be transmitted to the server using UTF-8 charset; you must decode this appropriately on the server side.




回答3:


you can also force your data to be a json in the success function: data = JSON.parse(data);




回答4:


this also works for me

$.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
  },
});


来源:https://stackoverflow.com/questions/5529685/post-doesnt-send-data-as-json-but-as-x-www-form-urlencoded-instead

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!