Getting Started With: by Dave Crane
Getting Started With: by Dave Crane
By Dave Crane
getting started Getting toKnow HTTP
The standard way to do Ajax is to use the XMLHttpRequest object, known as XHR by its friends. Use XHR directly, or via one of the helpful Ajax libraries such as Prototype or jQuery. How do we use XHR by hand? To start with, we need to get a reference to it: To make use of the XHR to its fullest, we recommend you become familiar with the workings of the HTTP protocol. Using Ajax, you have much more control over HTTP than with classic web app development.
if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) { xhr = new ActiveXObject(Microsoft.XMLHTTP); }
request headers
We can then open a connection to a URL: Specify a callback function to receive the response: and then send the request: The server may be busy, or the network may be slow. We dont want to sit around doing nothing until the response arrives, and because weve assigned the callback function, we dont have to. Thats the five-minute guide for the impatient. For those who like to know the details, weve listed the fuller details of the XHR object below.
browser body
Both request and response contain headers and an optional body, which is free text. Only a POST request contains a body. A request defines a verb or method. The Mime type of request and response can be set by the header Content-type
Parameters and Descriptions
xhr.send(null);
Method Name
open a connection to a URL method = HTTP verb (GET, POST, etc.) url = url to open, may include querystring async = whether to make asynchronous request assign a function object as callback (similar to onclick, onload, etc. in browser event model) add a header to the HTTP request send the request body = string to be used as request body stop the XHR from listening for the response stage in lifecycle of response (only populated after send() is called) The HTTP return code (integer, only populated after response reaches the loaded state) body of response as a JavaScript string (only set after response reaches the interactive readyState) body of the response as a XML document object (only set after response reaches the interactive readyState) read a response header by name Get an array of all response header names
onreadystatechange
responseText
responseXML