Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^278) CHAPTER 18 ■ AJAX AND JSON
if(key == "date") {
return new Date(value);
} else {
return value;
}
}
function showJsonData() {
//Create an object
original = {'date':'01/01/2007', 'data':'some data'};
json = original.toJSONString();
div = document.getElementById("jsonData");
restored = json.parseJSON(convertDates);
div.innerHTML = restored['date'].toString();
}





Show JSON Data



Mon Jan 1 00:00:00 MST 2007

The XMLHttpRequest Object


The next important part of JavaScript’s role in JSON communication is the XMLHttpRequest
(XHR) object. This is the object that allows you to communicate JSON data to PHP. The code
in Listing 18-5 shows a safe way of getting a cross-browser instance of the XHR object.

Listing 18-5. Cross-Browser XHR Retrieval

function getXHR() {
var req;
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
return req;
}

The reason for this extra complexity is that older versions of Internet Explorer, while fully
supporting XHR, do so through an ActiveX object, rather than with native functionality as occurs in

McArthur_819-9.book Page 278 Friday, February 29, 2008 8:03 AM

Free download pdf