varreq=newXMLHttpRequest();req.open("GET","example/data.txt",false);req.send(null);consle.log(req.responseText);// → This is the content of data.txt
console.log(req.status,req.statusText);// → 200 OK
console.log(req.getResponseHeader("content-type"));// → text/plain
If we pass true as the third argument to open, the request is asynchronous.
Browsers protect us by disallowing scripts to make HTTP requests to other domains
Servers can include a header in their response to explicitly indicate to browsers that it is okay for the request to come from other domains: Access-Control-Allow-Origin: *
Promises
Promises wrap an asynchronous action in an object, which can be passed around and told to do certain things when the action finishes or fails.
The promise acts as a handle to the request’s outcome.
1
2
3
4
5
6
7
8
get("example/data.text").then(function(text){console.log("data.text: "+text);},function(error){console.log("Failed to fetch data.text: "+error);});
Calling then produces a new promise, whose result (the value passed to success handlers) depends on the return value of the first function we passed to then.
Forms and Form Fields
We can control focus from JavaScript with the focus and blur methods.
The value in document.activeElement corresponds to the currently focused element.
HTML also provides the autofocus attribute, which produces the same effect but lets the browser know what we are trying to achieve.
Browsers traditionally also allow the user to move the focus through the document by pressing the Tab key.
We can influence the order in which elements receive focus with the tabindex attribute.
By default, most types of HTML elements cannot be focused. But you can add a tabindex attribute to any element, which will make it focusable.
Storing data client-side
You can store string data in a way that survives page reloads by putting it in the localStorage object.