HTML and CSS Reference
In-Depth Information
transmitted to the endpoint specified in the URL of the open method. The following code
sends the XML data to the server:
var xmlData = "<Person firstname='Rick' lastName='Delorme' hairColor='Brown'
eyeColor='Brown' /> ";
var xReq = new XMLHttpRequest();"POST", "/ReceiveXMLData.aspx", false);
When data is transmitted to the server, it needs to be serialized into a format that the
URL endpoint can understand. If the endpoint is expecting XML, the data must be XML; if it's
expecting binary data, the data must be in a binary format.
Serializing and deserializing JSON data
The browser provides native support for working with JSON and XML. The JSON object
is available for converting a JSON string to and from an object (serialize/deserialize). The
following code shows how this is accomplished:
var person = {
FirstName: "Rick",
HairColor: "Brown"
var jsonPerson = JSON.stringify(person);
The person object has been serialized into a JSON string that can be sent to an endpoint
URL for processing. To return the person back to a person object from a JSON string, the
object can be deserialized by using the parse method:
var req = new XMLHttpRequest();"GET", "MyJsonData.json", false);
var jsonPerson = JSON.parse(req.responseText);
When this code runs, the person object is reconstructed from the JSON string.
Serializing and deserializing binary data
Capturing dynamic image data follows a similar pattern as with the other techniques
reviewed. The key difference is now the responsetype property must be set to blob . The
following code demonstrates retrieving a binary image object and deserializing it into the
var xReq = new XMLHttpRequest();"GET", "orange.jpg", false);
xReq.responseType = 'blob';
var blob = xReq.response;
document.getElementById("result").src = URL.createObjectURL(blob);
Search WWH ::

Custom Search