JavaScript XMLHttpRequest
XMLHttpRequest is a JavaScript object type that can be used to retrieve a resource via a URL. Despite the Http
in the name of the type, an XMLHttpRequest object can be used to retrieve resources via various protocols including the
- http,
- ftp, and
- file protocols.
First, create an instance of XMLHttpRequest:
var req = new XMLHttpRequest();
Add any necessary event listeners to the request:
req.addEventListener("load", function(ev){alert("status=" + req.status);});
req.addEventListener("error", function(ev){alert("handle error");});
- If you attempt to access
statusorstatusTextwhenreadyStateis notDONEyou will get an INVALID_STATE_ERR DOM Exception 11 error. In any event other thanloadorerror, which are only called when readystate isDONE, be sure to doif (req.readyState == 4)before checkingreq.stateorreq.readyState. - If the destination site is a different domain than the origin, you need to add headers at the destination site to avoid errors such as XMLHttpRequest cannot load ... with Origin http://www.origin.com is not allowed by Access-Control-Allow-Origin or Request header field Content-Type is not allowed by Access-Control-Allow-Headers.
- In addition, when the destination is different from the origin, the only status that is returned is 200 OK; otherwise the req.status is zero, even when an HTTP error such as 404 Not Found has occurred.
To send a GET request:
var url = "http://www.ExampleOnly.com/demo/env.php?query¶m=value";
req.open("GET", url, true);
req.send(null);
- In the third parameter of
req.open, specifytruefor an asynchronous request orfalsefor a synchronous request
To send a POST request:
var url = "http://www.ExampleOnly.com/demo/env.php;
req.open("POST", url, true);
var formData = new FormData();
formData.append("param", "value");
req.send(formData);
- In the third parameter of
req.open, specifytruefor an asynchronous request orfalsefor a synchronous request