Book Image

JavaScript JSON Cookbook

By : Ray Rischpater, Brian Ritchie, Ray Rischpater
Book Image

JavaScript JSON Cookbook

By: Ray Rischpater, Brian Ritchie, Ray Rischpater

Overview of this book

Table of Contents (17 chapters)
JavaScript JSON Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Parsing the returned JSON


Once the server returns the result, you need a way to get that result from the XMLHttpRequest object and convert the result from a string to a JavaScript object.

How to do it...

The XMLHttpRequest object defines the onreadystatechange attribute to which you assign a function that is called periodically throughout the lifespan of a request. Here's our doAjax function in its entirety, including a function assigned to this attribute to monitor the request for completion:

function doAjax() {
  var xmlhttp;
  xmlhttp = new XMLHttpRequest();

  var request = { 
    call: "kf6gpe-7"
  };

  xmlhttp.addEventListener("loadstart", loadstart, false);
  xmlhttp.addEventListener("progress", progress, false);  
  xmlhttp.addEventListener("load", load, false);
  xmlhttp.addEventListener("abort", abort, false);
  xmlhttp.addEventListener("error", error, false);

  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 &&xmlhttp.status == 200)
    {
    ...