JSON APIs and Ajax

Time:2022-10-8

JSON APIs and Ajax

onclick

Want the code to execute only after the page has finished loading. will be namedDOMContentLoadedJavaScript events attached to the document. Here is the implemented code:

document.addEventListener('DOMContentLoaded', function() {

});

existDOMContentLoadedAdd an event handler method inside the function. can be addedonclickEvent handler, when the user clicks on the id ofgetMessageThe event fires when the element of the . Add the following code:

document.getElementById('getMessage').onclick = function(){};
<script>
  document.addEventListener('DOMContentLoaded', function(){document.getElementById("getMessage").onclick = function() {}
  });
</script>

click event change text click event

Use JavaScript to update HTML elements when a click event occurs.

For example, when the user clicksGet Messagebutton, it will change the class tomessageThe text of the element isHere is the message

Do this by adding the following code inside the click event:

document.getElementsByClassName('message')[0].textContent="Here is the message";

Get JSON using XMLHttpRequest method

Data can be requested from external sources. This is where the API comes into play.

An API (or application programming interface) is a tool that computers use to communicate with each other. HTML is updated with data obtained from the API via AJAX techniques.

Most web APIs transmit data in JSON format. JSON is shorthand for JavaScript Object Notation.

JSON syntax is very similar to JavaScript object literal notation. JSON has object properties and their current values, sandwiched in{and}between.

These properties and their values ​​are often referred to as “key-value pairs”.

However, JSON is served by the API asbytestransmitted in the form ofstringreceive it. They can be converted to JavaScript objects, but by default they are not JavaScript objects.JSON.parseThe method parses the string and constructs the JavaScript object it describes.

Request JSON from freeCodeCamp’s Cat Photo API. Here is the code added in the click event:

const req = new XMLHttpRequest();
req.open("GET",'/json/cats.json',true);
req.send();
req.onload = function(){
  const json = JSON.parse(req.responseText);
  document.getElementsByClassName('message')[0].innerHTML = JSON.stringify(json);
};

Here is what each line of code does. JavaScriptXMLHttpRequestObjects have many properties and methods for transferring data. First, create aXMLHttpRequestobject instance and saved inreqin the variable. Then,openmethod initiates a request – this example is requesting data from the API, so it is aGETask. second parameteropenis the URL of the API to request data from. The third parameter is a boolean value,trueMake it an asynchronous request.sendmethod to send the request. at last,onloadThe event handler parses the returned data and applies theJSON.stringifymethod converts the JavaScript object to a string, then inserts this string as message text

fetch

Another way to request external data is to use JavaScriptfetch()method. its role andXMLHttpRequestsame, but with a more understandable syntax.

Below is the request using GET/json/cats.jsonexample of data.

fetch('/json/cats.json')
    .then(response => response.json())
    .then(data => {
        document.getElementById('message').innerHTML = JSON.stringify(data);
    })

Explain the code line by line.

The first line is to initiate the request.fetch(URL)Initiate to the specified URLGETask. This method returns a Promise.

When the Promise returns, if the request is successful, it will be executedthenmethod, which converts the response to JSON format.

thenThe method returns a Promise, which will be used by the nextthenmethod capture. the secondthenThe parameter passed in by the method is the final JSON object.

Next, usedocument.getElementById()Select the element that will receive the data. Then insert the string created by the JSON object returned by the request to modify the HTML code of the element

Access JSON data from API

Recall some symbols in JavaScript:

[ ] -> Square brackets indicate an array
{ } -> curly brackets denote objects
” ” -> double quotes represent strings, they are also used to represent key names in JSON

Understanding the structure of the data returned by the API is required and will affect how you get the values ​​you need.

[{“id”:0,”imageLink”:”https://imgs.developpaper.com/imgs/funny-cat.jpg”,”altText”:”A white cat wearing a green, helmet shaped melon on its head. “,”codeNames”:[“Juggernaut”,”Mrs. Wallace”,”Buttercup”]},{“id”:1,”imageLink”:”https://imgs.developpaper.com/imgs/grumpy-cat.jpg”,”altText”:”A white cat with blue eyes, looking very grumpy. “,”codeNames”:[“Oscar”,”Scrooge”,”Tyrion”]},{“id”:2,”imageLink”:”https://imgs.developpaper.com/imgs/mischievous-cat.jpg”,”altText”:”A ginger cat with one eye closed and mouth in a grin-like expression. Looking very mischievous. “,”codeNames”:[“The Doctor”,”Loki”,”Joker”]}]

The first and last characters in JSON data are square brackets[ ], which means that the returned data is an array. The second symbol in JSON data is a curly bracket{, which means an object. Take a closer look and you’ll see that there are three separate objects. This JSON data is an array of three objects. In the first object there is an interesting “key-value pair” which is"codeNames":["Juggernaut","Mrs. Wallace","ButterCup"]codeNamesis the key and its value is an array of three strings. Arrays of objects and arrays as keys can be used as values.

Remember how to access data in arrays and objects. Arrays use bracket notation to access a specific index of an item, objects use bracket or dot notation to access the value of a given property. This example prints the first cat photoaltTextProperties – Note that the JSON data parsed in the editor is saved in a file namedjsonin the variable:

console.log(json[0].altText);

The console will display the stringA white cat wearing a green helmet shaped melon on its head.

Convert JSON to HTML

The data is fetched from the JSON API and can be displayed in HTML.

Since cat photo objects are stored in arrays, useforEachmethod to iterate over them. HTML elements can be modified as each object is fetched.

First, bylet html = "";Declare an html variable.

Next, traversing the JSON, we will usestrongThe tag-wrapped key name and the html element followed by the value are added to the variable. Render it when the loop is over. Here is the code to do this:

let html = "";
json.forEach(function(val) {
  const keys = Object.keys(val);
  html += "<div class = 'cat'>";
  keys.forEach(function(key) {
    html += "<strong>" + key + "</strong>: " + val[key] + "<br>";
  });
  html += "</div><br>";
});

Notice:usetextContentmethod. useinnerHTMLWebsites are vulnerable to cross-site scripting attacks.

Render the image of the data source

Each object in the JSON array contains aimageLinkkey whose value is the URL of the cat image.

When iterating over these objects, useimageLinkproperty inimgelement to display this image.

Here is the code to do this:

html += "<img src = '" + val.imageLink + "' " + "alt='" + val.altText + "'>";

Pre-filter JSON

Given that JSON data is stored in an array, usefiltermethod to filter outidkey value1the cat.

Here is the code to do this:

json = json.filter(function(val) {
  return (val.id !== 1);
});

Find the user’s GPS coordinates based on geolocation data

Access your user’s current geographic location. Every browser has a built-in navigator.

The navigator gets the user’s current longitude and latitude.

Here is the code to do this:

if (navigator.geolocation){
  navigator.geolocation.getCurrentPosition(function(position) {
    document.getElementById('data').innerHTML="latitude: " + position.coords.latitude + "<br>longitude: " + position.coords.longitude;
  });
}

Send data using XMLHttpRequest

Additionally, data can be sent to an external resource as long as the resource supports AJAX requests and knows the URL. JavaScriptXMLHttpRequestMethods are also used to post data to the server. Here is an example:

const xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 201){
    const serverResponse = JSON.parse(xhr.response);
    document.getElementsByClassName('message')[0].textContent = serverResponse.userName + serverResponse.suffix;
  }
};
const body = JSON.stringify({ userName: userName, suffix: ' loves cats!' });
xhr.send(body);