Johan Kohlin
Lecturer at School of engineering, Jönköping University.
Asynchronous JavaScript and XML
let's see how that works
Create a request object
var myRequest = new XMLHttpRequest()
myRequest is now an object containing methods for fetching data from a file
Deciding the type of data to expect
myRequest.responseType = "text"
Possible response types:
"arraybuffer" | An immutable array of binary raw data |
"blob" | A file as an object with raw data |
"document" | If the requested files is an SVG, HTML or XML file you'll get a DOM object back. |
"json" | If the requested file contains a json string you will get a parsed object back |
"text" (default) | Whatever document you request, you get the result as a string. |
Initialising the request
var method = "GET";
var url = "footer.html";
myRequest.open(method, url);
This is where you decide which file you want to read.
Normally, you can only get files from the server we do the request from.
Some servers provide support for CORS which tells your browser that it's ok and safe to get this file.
Sending the request
myRequest.send();
This is where the request is sent.
Since the default setting is to make an asynchronous request,
meaning we don't know how long it's going to take,
we now have to wait for the response...
Waiting for the response
myRequest.addEventListener("load",dealWithResponse);
As soon as the requested document has arrived,
the "load" event will fire and your function
(dealWithResponse) will be called.
Dealing with the response
myRequest.addEventListener("load",dealWithResponse);
function dealWithResponse(){
document.body.innerHTML = myRequest.response;
}
myRequest.response will contain your requested data
in the format you decided on in step #2
In this case we chose text and we requested an html document
the result will be the html code from that document as a string.
Requesting data from a public API that support CORS
By Johan Kohlin