Sending JSON to your web server
Some AJAX requests just need to get data at a URL. This is the case when the server updates an object for all clients, or when the URL for an object uniquely identifies the object (common when you design a service using Representational State Transfer (REST)). Other times, you may want to pass JavaScript data to the server, such as when you have a complex query you'd like the server to process. To do this, create your JavaScript object, then stringify it and pass the string containing the JSON to the XMLHttpRequest
object's send
method.
How to do it...
Omitting the code that creates an XMLHttpRequest
object, you send JSON to a server with the following code:
function doAjax() { // … create XMLHTTPObject as before var request = { call: "kf6gpe-7" }; xmlhttp.open("POST","/", true); xmlhttp.setRequestHeader("Content-Type","application/json"); xmlhttp.send(JSON.stringify(request))...