$.post()
doesn't do the trick...Well it's not impossible but very inconvenient if you have to do it a lot. First you need to use the
$.ajax()
method, not the $.post()
one. Secondly you need to specify the contentType
parameter for the receiver to be notified that the data is in that format. And last but not least it is crucial to properly serialize your object to string.The last part can be done using
JSON.stringify()
but writing this over and over again is painful. Here's a gist (raw) you can use that adds a sister version of $.post
called $.postJSON
that does exactly the same thing as the original one but sends data in JSON format instead of form post.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function($) { | |
$.postJSON = function(url, data, success, dataType) { | |
if (typeof data != 'string') { | |
data = JSON.stringify(data); | |
} | |
$.ajax({ | |
url : url, | |
type: "post", | |
data: data, | |
dataType: dataType || "json", | |
contentType: "application/json", | |
success: success | |
}); | |
} | |
})(jQuery); |
Happy coding!
No comments:
Post a Comment