Hey Chris,
I built a two way JSON web service which is working really well. It
simplifies the hell out of the code at either end. Particularly when
you are making intricate updates/requests.
The way it works is that each call I make is actually done using xhr
method POST. I'm specifying the action to be performed in the json not
the url.
So action "getUserDetails" would be a call to "php/api.php" with the
POST data: { "action":"get_user_details" }
Here is my xhr code:
///////////////////// js //////
self.xhr("POST", "php/api.php",
data,
function(status, response) {
if (200 <= status && status < 300) {
// all good
} else {
// error
}
});
///////////////////
'data' is a native object, no need to turn it to a JSON string. Also
the response object that comes back will also be a native object.
That works fine and the POST data will contain raw JSON, the tricky
part is retrieving the data on the server side. Now I'm using PHP so
normally I would get POST data using $_POST['action'] however this
wont work because the post data is raw JSON not flat key-value pairs.
Here is how I retrieve the JSON POST data in php:
///////////// php ////
// reads input stream as a string
$rawrequest = file_get_contents('php://input');
$req = json_decode($rawrequest,true);
///////////////////////
$req is now a native associative array with all the structure of the
'data' object you sent to xhr. I have found this is unbelievably handy
in the app I'm building.
Here is how best to respond:
/////////////// php ///
header('Content-type: application/json');
echo json_encode($response);
exit ();
//////////////////////
Now if you're not using PHP you will have to find the equivalent of
this.
Best of luck, let me know how you get on.
rur