A client-side XHR request for getting data from a URL, formally known as XMLHttpRequest.
A client-side XHR request for getting data from a URL, formally known as XMLHttpRequest.
HttpRequest can be used to obtain data from HTTP and FTP protocols, and is useful for AJAX-style page updates.
The simplest way to get the contents of a text file, such as a JSON-formatted file, is with getString. For example, the following code gets the contents of a JSON file and prints its length:
var path = 'myData.json';
HttpRequest.getString(path)
.then((String fileContents) {
print(fileContents.length);
})
.catchError((Error error) {
print(error.toString());
});
For security reasons, browsers impose restrictions on requests made by embedded apps. With the default behavior of this class, the code making the request must be served from the same origin (domain name, port, and application layer protocol) as the requested resource. In the example above, the myData.json file must be co-located with the app that uses it. You might be able to get around this restriction by using CORS headers or JSONP.
Fetch Data Dynamically, a tutorial from A Game of Darts, shows two different ways to use HttpRequest to get a JSON file.
Get Input from a Form, another tutorial from A Game of Darts, shows using HttpRequest with a custom server.