Invalid Json Usages?
Solution 1:
$.ajax("/", {
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
'page': '100AAAAAf00'
},
type: 'POST',
responseType: "json"
});
Is wrong. This will send a normal application/x-www-form-urlencoded request with the request body:
page=100AAAAAf00
But since the header is "application/json; charset=utf-8", it is actually lying to the server.
To send, real, pure, actual JSON to the server with jQuery, you would use:
$.ajax("/", {
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ //If data is string, jQuery will not try to process it'page': '100AAAAAf00'
}),
type: 'POST',
responseType: "json"
});
Now the request body will be:
{"page":"100AAAAAf00"}And that cannot be used with php's $_POST at all since it works on the basis of application/x-www-form-urlencoded,
so maybe that's why people prefer the former..
One can use Chrome's network tab in developer tools to verify my claims here:
http://jsfiddle.net/sV5m4/1/ - Actual json with json header

and here:
http://jsfiddle.net/sV5m4/2/ - x-www-form-urlencoded with header that claims to be json

Solution 2:
There is a simple function to convert an object to a JSON string...
JSON.stringify({ 'page': '100AAAAAf00' }) // => '{ "page": "100AAAAAf00" }'The other way around...
JSON.parse('{ "page": "100AAAAAf00" }') // => { page: '100AAAAAf00' }Solution 3:
In your example everything is correct and data property is an object.
Due to jQuery.ajax(); docsdata property could be object, array or string.
If it's an array or an object jQuery serializes it.
Post a Comment for "Invalid Json Usages?"