AJAX with JSON
Table of Content:
AJAX with JSON
Some link contains JSON data. With the help of that we can play with them. For example in this link (https://jsonplaceholder.typicode.com/todos/1) you will get below sample data. You can fetch this data using AJAX. Let's see how you will be able to get that data in your project.
{ "userId": 1, "id": 1, "title": "delectus aut autem", "completed": false }
HTML Code
Hello, world! Hello, world!
This is demo Div
SCRIPT Code
- Here we used JSON.parse()
- We got the element using document.getElementById("demo"), then appended data on that div.
headers('Content-Type: application/json;'); function loadDoc() { const xhttp = new XMLHttpRequest(); xhttp.onload = function() { myObj = JSON.parse(this.responseText); let element = document.getElementById("demo"); element.append(" --- User Id - "+myObj.userId); element.append(" --- completed - "+myObj.completed); element.append(" --- Title - "+myObj.title); } xhttp.open("GET", "https://jsonplaceholder.typicode.com/todos/1"); xhttp.send(); }
If you will run above code, you will get below output.