Working with Resources

R. Alexander Miłowski

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!


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
                   ⇓ Open the URI asynchronously"GET","",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"GET","",true);

What is the difference in the above calls?

The second one is synchronous ...

Everything stops until the response is processed.