A Uniform Resource Locator (URL), is a reference to a web resource that
specifies its location on a computer network and a mechanism for retrieving it.
A web resource is any data that can be obtained via web, such as HTML documents,
PDF files, PNG images, JSON data, or plain text.
JSON (JavaScript Object Notation) is a lightweight data-interchange format.
It is easy for humans to read and write and for machines to parse and generate.
The official Internet media type for JSON is application/json.
The JSON filename extension is .json.
In our examples, we use JSON data from http://time.jsontest.com.
jQuery is a JavaScript library which is used to manipulate DOM.
With jQuery, we can find, select, traverse, and manipulate parts of a HTML document.
The JQuery $.getJSON() method loads JSON-encoded data from a server
using a GET HTTP request.
jQuery.getJSON( url [, data ] [, success ] )
This is the method signature. The url parameter is
a string containing the URL to which the request is sent.
The data is a plain object or string that is sent
to the server with the request. The success is
a callback function that is executed if the request succeeds.
The example reads JSON data with Fetch API and prints the returned data to the console.
To see the output, we need to activate the developer console of our browser.
The fetch() method takes one mandatory argument, the path to the
resource we want to fetch. It returns a promise that resolves
to the response of the request.
Reading JSON with XMLHttpRequest
XMLHttpRequest API provides client functionality for
transferring data between a client and a server. It allows an easy way to
retrieve data from a URL without having to do a full page refresh.
As a consequence, a web page has to update just a part of the page without disrupting
what the user is doing. XMLHttpRequest is used heavily in AJAX programming.
<script>
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.send();
};
getJSON('http://time.jsontest.com', function(err, data) {
if (err != null) {
console.error(err);
} else {
var text = `Date: ${data.date}
Time: ${data.time}
Unix time: ${data.milliseconds_since_epoch}`
console.log(text);
}
});
</script>
This example reads JSON data with XMLHttpRequest.
var xhr = new XMLHttpRequest();
A new instance of XMLHttpRequest is created.
xhr.open('GET', url, true);
The open() method initializes a request.
xhr.responseType = 'json';
The responseType value defines the response type.
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
In the onload() method, we wait for the response from the server.
xhr.send();
The send() method sends the request; the request is asynchronous
by default.
Tidak ada komentar:
Posting Komentar