jeudi 23 août 2012

Basic JavaScript - HTTP Requests

This post corresponds to notes taken while reading Eloquent JavaScript.

To be able to request information from a web page, first, we create an object to make an HTTP request with the help of XMLHttpRequest() method. Second, the open method is used to configure the HTTP request, it specifies GET as the method, and "page.html" as the requested resource from the server. The third parameter indicates whether the request is performed synchronously in case it is false, or asynchronously if it is true. Finally, the send method made the request. Its parameter indicates the data to be sent to the server. Here it is set to null as we made a GET request.
var request = new XMLHttpRequest();
request.open("GET", "page.html", true);
request.send(null);
request.onreadystatechange = function() {
 if (request.readyState == 4)
  console.log(request.responseText.length);
};
When response is received from the server:
  • resposeText: contains the content of the server response, if it is in XML then it could be retrived as DOM from responseXML.
  • getAllResponseHeaders(): returns all headers of the response
  • getResponseHeader("Date"): returns value of the corresponding header, here Date.
  • setRequestHeader(key, value): can be used to set the value of a header for the current HTTP request.
  • status property contains the response code 200 for OK, 404 for resource doesn't exist, 300 for redirection.
  • statusText contains a description of the returned response code.
  • readyState used in the asynchronous case to indicate the state of the request: 0 'uninitialized' is the state before calling open(), calling open() moves it to 1 'open', calling send moves it to 2 'sent', a server response moves it to 3 'receiving', at the end the state become 4 'loaded'.
  • onreadystatechange is used to set a callback function that will be called when the state property of the request changes.
Common:
A JSON string can be converted to a JSON object with the eval function:
var json_obj = eval("(" + json_txt + ")");
The parenthesis are added to avoid interpreting the text as a block of code as it is enclosed by braces.

The document.body.linkBack property allows to set to the previously visited page.

Aucun commentaire:

Enregistrer un commentaire