CPSC415A
Web Programming

Day 11 Notes

JSON & AJAX

Parse JSON

var jsonString = '{"one": 1, "two": 2}';
var anObject = JSON.parse(jsonString);
console.log(anObject.one);

var jsonString = '[1, 2, 3]';
var anArray = JSON.parse(jsonString);
console.log(anArray[0]);

Stringify JSON

var anObject = {"one": 1, "two": 2};
var jsonString = JSON.stringify(anObject);
console.log(jsonString);

var anArray = [1, 2, 3];
var jsonString = JSON.stringify(anArray);
console.log(jsonString);

Initialize HTTP Request Object

var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = handleResponse;

Send HTTP Request

httpRequest.open('GET', 'http://useless.com/useless.json', true);
httpRequest.send();

Prevent Caching of HTTP Request

var time = (new Date()).getTime();
httpRequest.open('GET', 'http://useless.com/useless.json?' + time, true);
httpRequest.send();

Handle HTTP Request Response

var handleResponse = function() {
    if (httpRequest.readyState === XMLHttpRequest.DONE &&
        httpRequest.status === 200) {
        console.log(httpRequest.responseText);
    }
}