1.2. Making Ajax Calls Without Prototype
As with most things in JavaScript, using the XMLHttpRequest object (the heart of Ajax) is straightforward but verbose. If you've ever called an HTTP-based service, your code probably looks something like this:
xhr=null; function getData(url) { if (window.XMLHttpRequest) { xhr=new XMLHttpRequest() } else if (window.ActiveXObject) { xhr=new ActiveXObject("Microsoft.XMLHTTP") } if (xhr) { xhr.onreadystatechange=callback xhr.open("GET",url,true) xhr.send(null) } else { alert("XMLHTTP not supported") } } function callback() { // when finished if (xhr.readyState==4) { // OK if (xhr.status==200) { // process the result. } else { alert("error") } } }
With Prototype, this can be written as:
function getData(url) { var ar = new Ajax.Request(url,{ method: "get", onComplete : callback}); } function callback(request) { // process the result. var text = request.responseText; ... }
Get Prototype and Scriptaculous: Taking the Pain out of JavaScript now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.