04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 17: Ajax and JSON<br />

JSON is also a popular format for sending data to the server. This is typically done as the body of a POST<br />

request, and the JSON object ’s stringify() method is provided for this purpose. This method accepts three<br />

arguments: the object to serialize, an optional replacer function to replace unsupported JSON values, and an<br />

optional indentation specifier that can be either the number of spaces to indent each level or a character with<br />

which to indent. By default, stringify() returns an unindented JSON string as shown here:<br />

var contact = {<br />

name: “Nicholas C. Zakas”,<br />

email: “nicholas@some-domain-name.com”<br />

};<br />

var jsonText = JSON.stringify(contact);<br />

alert(jsonText);<br />

The alert displays the following text:<br />

{\”name\”:\”Nicholas C. Zakas\”,\”email\”:\”nicholas@some-domain-name.com \”}<br />

Since not all JavaScript values can be represented in JSON, the result will include only those that are<br />

officially supported. For instance, functions and undefined cannot be represented in JSON, so any key<br />

containing them will be removed by default. You can override this default behavior by providing a<br />

function as the second argument. The function is run within the scope of the object that is currently<br />

being serialized and is passed each key and value as arguments whenever an unsupported data type is<br />

encountered. The function is not called for known data types, which include strings, numbers, Booleans,<br />

null , objects, arrays, and Date (the latter is converted into a string representation of the date). Here is an<br />

example:<br />

var jsonText = JSON.stringify([new Function()], function(key, value){<br />

if (value instanceof Function){<br />

return “(function)”;<br />

} else {<br />

return value;<br />

}<br />

});<br />

alert(jsonText); //”[(function)]”<br />

This example attempts to serialize an array containing a function. When the function value is<br />

encountered, the second argument is used to convert the value into the string “ (function) ” that<br />

appears in the final output.<br />

JSON data can be sent to the server using a POST request and passing in the JSON text to the send()<br />

method. Consider the following example:<br />

var xhr = createXHR();<br />

var contact = {<br />

name: “Ted Jones”,<br />

email: “tedjones@some-other-domain.com”<br />

};<br />

xhr.onreadystatechange = function(){<br />

if (xhr.readyState == 4){<br />

if ((xhr.status > = 200 & & xhr.status < 300) || xhr.status == 304){<br />

alert(xhr.responseText);<br />

(continued)<br />

585

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!