Can I Read a Json File Without Ajax

JavaScript read JSON from URL

final modified October eighteen, 2021

JavaScript read JSON from URL tutorial shows how to read data in JSON format from the provided URL. We employ JQuery, Fetch API, and XMLHttpRequest.

URL

A Compatible 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 every bit HTML documents, PDF files, PNG images, JSON data, or manifestly text.

A generic URL has the following form:

scheme:[//[user:password@]host[:port]][/]path[?query][#fragment]        

The square brackets indicate that the office is optional. A scheme is a way of addressing resources, such every bit http, ftp, mailto, or file.

The part following ii slashes is chosen the authority office. The authority part contains 1) an optional authentication section of a user name and countersign, separated past a colon, followed by an at symbol (@) ii) a host, which is either a host name of or an IP address, 3) an optional port number, separated from the host by a colon.

A path is a route to the resource on the host. It may or may not resemble or map exactly to a file organization path. Query cord is used to add some criteria to the request for the resource. It is often a sequence of primal/value pairs. The final part is an optional fragment, which points to a secondary resource, such as a heading. Information technology is separated from the query cord past a hash (#).

JSON

JSON (JavaScript Object Note) 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, nosotros employ JSON information from http://time.jsontest.com.

{    "fourth dimension": "11:27:26 AM",    "milliseconds_since_epoch": 1494934046126,    "date": "05-sixteen-2017" }        

The Go request returns this JSON string.

Reading JSON with JQuery

jQuery is a JavaScript library which is used to manipulate DOM. With jQuery, we tin discover, select, traverse, and dispense parts of a HTML document.

The JQuery $.getJSON method loads JSON-encoded information from a server using a GET HTTP request.

jQuery.getJSON( url [, data ] [, success ] )        

This is the method signature. The url parameter is a cord 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 asking succeeds.

$.ajax({   dataType: "json",   url: url,   data: data,   success: success });        

$.getJSON is a autograph for the above call.

js_read_json_url.html

<!DOCTYPE html> <html lang="en"> <head> <title>JavaScript - read JSON from URL</title>     <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> </head>  <body>     <div class="mypanel"></div>      <script>     $.getJSON('http://time.jsontest.com', function(information) {          var text = `Date: ${data.date}<br>                     Time: ${data.time}<br>                     Unix time: ${data.milliseconds_since_epoch}`           $(".mypanel").html(text);     });     </script>  </body> </html>        

In the example, nosotros read JSON data from http://fourth dimension.jsontest.com. The returned object has three attributes: date, fourth dimension, and unix epoch.

var text = `Appointment: ${data.date}<br>             Fourth dimension: ${data.time}<br>             Unix time: ${data.milliseconds_since_epoch}`        

We build the message using the JavaScript template cord.

$(".mypanel").html(text);        

With JQuery'southward html method, we suspend the text to the div tag.

Reading JSON from URL with JQuery
Figure: Reading JSON from URL with JQuery

In the figure we can encounter the current engagement, time, and Unix time.

Reading JSON with Fetch API

Fetch API is interface for fetching resource. 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())     .and then((out) => {         console.log('Output: ', out); }).catch(err => console.error(err)); </script>        

The instance reads JSON data with Fetch API and prints the returned data to the console. To encounter the output, we demand 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 like shooting fish in a barrel style to retrieve data from a URL without having to practice a full page refresh. Equally a consequence, a spider web page has to update only a office of the page without disrupting what the user is doing. XMLHttpRequest is used heavily in AJAX programming.

<script>  var getJSON = part(url, callback) {      var xhr = new XMLHttpRequest();     xhr.open('GET', url, true);     xhr.responseType = 'json';      xhr.onload = part() {          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 != goose egg) {         console.error(err);     } else {          var text = `Date: ${data.date} Time: ${data.time} Unix time: ${data.milliseconds_since_epoch}`          panel.log(text);     } });  </script>        

This case 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 asking.

xhr.responseType = 'json';        

The responseType value defines the response type.

xhr.onload = office() {      var status = xhr.condition;      if (status == 200) {         callback(null, xhr.response);     } else {         callback(status);     } };        

In the onload method, we await for the response from the server.

xhr.send();        

The send method sends the request; the request is asynchronous past default.

In this tutorial, we have read JSON data in JavaScript with JQuery, Fetch API, and XMLHttpRequest.

List all JavaScript tutorials.

cooneythujered1941.blogspot.com

Source: https://zetcode.com/javascript/jsonurl/

0 Response to "Can I Read a Json File Without Ajax"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel