04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 17: Ajax and JSON<br />

Headers can be used to pass additional, structured data from the server to the browser. The<br />

getAllResponseHeaders() method typically returns something along the lines of the following:<br />

Date: Sun, 14 Nov 2004 18:04:03 GMT<br />

Server: Apache/1.3.29 (Unix)<br />

Vary: Accept<br />

X-Powered-By: PHP/4.3.8<br />

Connection: close<br />

Content-Type: text/html; charset=iso-8859-1<br />

This output allows you to parse the response headers to find all of the header names that were sent<br />

rather than checking for the existence of each one individually.<br />

GET Requests<br />

The most common type of request to execute is a GET, which is typically made when the server is being<br />

queried for some sort of information. If necessary, query - string arguments can be appended to the end of<br />

the URL to pass information to the server. For XHR, this query string must be present and encoded<br />

correctly on the URL that is passed into the open() method.<br />

One of the most frequent errors made with GET requests is to have an improperly formatted query<br />

string. Each query - string name and value must be encoded using encodeURIComponent() before being<br />

attached to the URL, and all of the name - value pairs must be separated by an ampersand, as in this<br />

example:<br />

xhr.open(“get”, “example.php?name1=value1 & name2=value2”, true);<br />

The following function helps to add query - string arguments to the end of an existing URL:<br />

function addURLParam(url, name, value) {<br />

url += (url.indexOf(“?”) == -1 ? “?” : “ & ”);<br />

url += encodeURIComponent(name) + “=” + encodeURIComponent(value);<br />

return url;<br />

}<br />

The addURLParam() function takes three arguments: the URL to add the parameters to, the parameter<br />

name, and the parameter value. First the function checks to see if the URL already contains a question<br />

mark (to determine if other parameters already exist). If it doesn ’ t, then the function appends a question<br />

mark; otherwise it adds an ampersand. Next the name and value are encoded and appended to the end<br />

of the URL. The last step is to return the updated URL.<br />

This function can be used to build up a URL for a request as shown in the following example:<br />

var url = “example.php”;<br />

//add the arguments<br />

url = addURLParam(url, “name”, “Nicholas”);<br />

url = addURLParam(url, “book”, “Professional JavaScript”);<br />

//initiate request<br />

xhr.open(“get”, url, false);<br />

573

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!