Working with Resources

R. Alexander Miłowski

milowski@ischool.berkeley.edu

School of Information, UC Berkeley

Web Resources are Data

If you just need to access a resource (e.g. JSON or XML) and

then, XMLHttpRequest is your tool!

XMLHttpRequest

A bit mislabeled today, but it is your way to talk HTTP!

var request = new XMLHttpRequest(); ⇐ creates the object
request.onreadystatechange = function() { ⇐ a callback that's a closure (?!)
   if (this.readyState==4) { ⇐ 4 is the magic number for done
      console.log(this.status);
      console.log(this.responseText);
   }
}
                   ⇓ Open the URI asynchronously
request.open("GET","http://www.mesonet.info/data/q/2.5/n/2975/",true);
request.send(); ⇐ Initiate the request
         

Basic Properties

readyStateA numberical code indicating the status of the request (0 - unsent, 1 - opened, 2 - headers received, 3 - loading, 4 - done)
responseTextThe textual value of the response (e.g., a sequence of characters)
responseXMLThe DOM object for the response.
statusThe HTTP status code (e.g., 200 - OK or 401 - Unauthorized)

Getting JSON:

var obj = JSON.parse(request.responseText);
obj.myproperty ...
         

Async vs Sync

request.open("GET","http://www.mesonet.info/data/q/2.5/n/2975/",true);
request.send();
    vs
request.open("GET","http://www.mesonet.info/data/q/2.5/n/2975/",false);
request.send();
         

What is the difference in the above calls?

The second one is synchronous ...

Everything stops until the response is processed.