Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
934 views
in Technique[技术] by (71.8m points)

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

This one is really weird. I have multiple $.post() in the code, but there is one don't know 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: Firefox screenshot

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...