Reading From a 2d Json Array Ajax Jquery
JavaScript read JSON from URL
final modified Oct 18, 2021
JavaScript read JSON from URL tutorial shows how to read information in JSON format from the provided URL. We utilize JQuery, Fetch API, and XMLHttpRequest.
URL
A Uniform Resource Locator (URL), is a reference to a web resource that specifies its location on a computer network and a machinery for retrieving it. A web resource is whatsoever data that tin can exist obtained via web, such as HTML documents, PDF files, PNG images, JSON data, or apparently text.
A generic URL has the following form:
scheme:[//[user:password@]host[:port]][/]path[?query][#fragment]
The square brackets indicate that the function is optional. A scheme is a way of addressing resources, such every bit http, ftp, mailto, or file.
The role following two slashes is called the authority part. The say-so role contains 1) an optional hallmark section of a user name and countersign, separated by a colon, followed by an at symbol (@) 2) a host, which is either a host proper noun of or an IP accost, iii) an optional port number, separated from the host by a colon.
A path is a road to the resource on the host. It may or may non resemble or map exactly to a file system path. Query string is used to add some criteria to the request for the resource. Information technology is often a sequence of key/value pairs. The final part is an optional fragment, which points to a secondary resource, such every bit a heading. Information technology is separated from the query string by a hash (#).
JSON
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 blazon for JSON is application/json
. The JSON filename extension is .json
.
In our examples, we use JSON information from http://time.jsontest.com
.
{ "time": "xi:27:26 AM", "milliseconds_since_epoch": 1494934046126, "date": "05-16-2017" }
The GET request returns this JSON string.
Reading JSON with JQuery
jQuery is a JavaScript library which is used to manipulate DOM. With jQuery, we can observe, 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 asking is sent. The data
is a evidently 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.
$.ajax({ dataType: "json", url: url, data: data, success: success });
$.getJSON
is a autograph for the above telephone call.
js_read_json_url.html
<!DOCTYPE html> <html lang="en"> <head> <title>JavaScript - read JSON from URL</title> <script src="https://lawmaking.jquery.com/jquery-3.2.one.min.js"></script> </head> <torso> <div class="mypanel"></div> <script> $.getJSON('http://fourth dimension.jsontest.com', office(information) { var text = `Date: ${data.date}<br> Fourth dimension: ${information.time}<br> Unix time: ${data.milliseconds_since_epoch}` $(".mypanel").html(text); }); </script> </torso> </html>
In the instance, nosotros read JSON information from http://time.jsontest.com
. The returned object has 3 attributes: appointment, fourth dimension, and unix epoch.
var text = `Date: ${data.date}<br> Time: ${data.time}<br> Unix time: ${information.milliseconds_since_epoch}`
We build the message using the JavaScript template cord.
$(".mypanel").html(text);
With JQuery'southward html
method, nosotros append the text to the div
tag.
![Reading JSON from URL with JQuery](https://zetcode.com/img/art/javascriptjsonurl/javascript_json_url.png)
In the figure nosotros can encounter the current date, time, and Unix time.
Reading JSON with Fetch API
Fetch API is interface for fetching resources. It is similar to XMLHttpRequest
but its API provides a more powerful and flexible feature set.
<script> fetch('http://time.jsontest.com') .then(res => res.json()) .then((out) => { console.log('Output: ', out); }).catch(err => console.error(err)); </script>
The example reads JSON data with Fetch API and prints the returned data to the console. To encounter the output, we need to activate the developer panel of our browser.
The fetch
method takes one mandatory statement, 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 practise a total folio refresh. As a outcome, a web page has to update but 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('Go', 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, information) { if (err != nix) { panel.error(err); } else { var text = `Date: ${data.date} Time: ${data.time} Unix time: ${data.milliseconds_since_epoch}` panel.log(text); } }); </script>
This example reads JSON information with XMLHttpRequest
.
var xhr = new XMLHttpRequest();
A new instance of XMLHttpRequest
is created.
xhr.open('GET', url, true);
The open up
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, nosotros await for the response from the server.
xhr.send();
The transport
method sends the request; the request is asynchronous by default.
In this tutorial, nosotros take read JSON data in JavaScript with JQuery, Fetch API, and XMLHttpRequest.
List all JavaScript tutorials.
Source: https://zetcode.com/javascript/jsonurl/
0 Response to "Reading From a 2d Json Array Ajax Jquery"
Postar um comentário