Retrieve JSON information from a document through JavaScript

Is it possible to fetch JSON data using JavaScript without relying on jQuery? I am only interested in retrieving data using pure JavaScript.

Here is an example of my JSON file:

{"JsonProjectIDResult":[{"_capacity":15,"_description":"Meeting Room","_dev_default_view":3,"_deviceID":1,"_deviceName":"MobiTech","_deviceTypeID":1,"_projectID":1,"_roomID":2,"_roomName":"Room2","_room_admin_mail":null}]}

This is what my home.html file looks like:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8>
  <title>JavaScript Get Json</title>

</head>
<body>

<h1>My Home Page</h1>

<div id="results">
    <!-- Display Jason Data -->
</div>

<script>

    var resultDiv = document.getElementById("results");

    var newsURL = "http://localhost:81/testjs/data.json";

    var req;

    if (window.XMLHttpRequest) {
        // code for modern browsers
        req = new XMLHttpRequest();
    } else {
        // code for old IE browsers
        req = new ActiveXObject("Microsoft.XMLHTTP");
    }

    req.onreadystatechange = function() {

        var html = "";

        if (req.readyState == 4 && req.status == 200) {
            var response = JSON.parse(req.responseText);

            if(typeof(req.responseText)==="string") {
                dataVar = req.responseText;
            } else {
                if (typeof(req.responseXML)==="object") {
                    dataVar = req.responseXML;
                };
            }

            var myData = response['JsonProjectIDResult'];

            //Print results 
            html += myData[0]._capacity+"<br />";
            html += myData[0]._description+"<br />";
            html += myData[0]._dev_default_view+"<br />";
            html += myData[0]._deviceID+"<br />";
            html += myData[0]._deviceName+"<br />";
            html += myData[0]._deviceTypeID+"<br />"; 
            html += myData[0]._projectID+"<br />"; 
            html += myData[0]._roomID+"<br />"; 
            html += myData[0]._roomName+"<br />"; 
            html += myData[0]._room_admin_mail+"<br />";

            resultDiv.innerHTML = html;
        }
    };

    req.open("GET", newsURL, true);
    req.send();

</script>

</body>
</html>

After receiving some helpful advice from friends, I have modified my code accordingly and now it works as expected. Next, I am looking to iterate through the records using a loop. Is it possible to achieve this using JavaScript?

Answer №1

<script>
var resultsContainer = document.getElementById("results");

var dataURL = "http://example.com/data.json";


var xhr;

if (window.XMLHttpRequest) {
    // code for modern browsers
    xhr = new XMLHttpRequest();
} else {
    // code for older versions of IE
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
}

xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        response = JSON.parse(xhr.responseText);
        
        var jsonData = response['JsonData'];
        
        var htmlContent = '<ul>';
        for(var key in jsonData) {
            if(jsonData.hasOwnProperty(key))
                 htmlContent += '<li>' + key  + ' = ' + jsonData[key] + '</li>';
        }
        htmlContent += '</ul>';
        
        resultsContainer.innerHTML = htmlContent;
    }
}

xhr.open("GET", dataURL, true);
xhr.send();
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process of using JavaScript code to read a text file?

Trying to use Google Charts while reading data from a text file. The code in JS is written for this purpose: function readTextFile(file){ var rawFile = new XMLHttpRequest(); rawFile.open("GET", file, false); // using synchronous call var allTe ...

Creating an optimized dashboard in Next.js: Expert tips for securing pages with specific roles, seamlessly implementing JWT authentication without any distracting "flickering" effect

Given our current setup: We have a backend ready to use with JWT authentication and a custom Role-Based Access Control system There are 4 private pages specifically for unauthenticated users (login, signup, forgot password, reset password) Around 25 priva ...

Transitioning from the traditional LeftNav menu style to the more versatile composability feature using Reactjs with Material-ui

Hey there, I'm facing a bit of confusion while trying to create a LeftNav menu using material-ui. I recently joined this project and updated reactjs and material-ui. Unfortunately, many things related to LeftNav in material-ui have been deprecated, ...

Arranging containers in a fixed position relative to their original placement

A unique challenge presents itself in the following code. I am attempting to keep panel-right in a fixed position similar to position: relative; however, changing from position: relative to position: fixed causes it to move to the right side while the left ...

Arrange the Proxy Array of Objects, the localeCompare function is not available

Encountering an error while attempting to implement ES6 arrayObj.sort(a,b) => a.property.localeCompare(b.property) syntax: Getting TypeError: a.property.localeCompare is not a function. Suspecting that localeCompare might not be in scope, but unsure ...

Using the Vue.js Compositions API to handle multiple API requests with a promise when the component is mounted

I have a task that requires me to make requests to 4 different places in the onmounted function using the composition api. I want to send these requests simultaneously with promises for better performance. Can anyone guide me on how to achieve this effic ...

Having trouble saving to a JSON file. The fs.writeFile function seems to be malfunctioning

I am currently working on a piece of code that involves fs.writeFile. The goal is to update the localdata.json file whenever a new workout is POST'ed to the database. This code takes data from the local state and attempts to write it into the file. U ...

When scrolling, a new page loads seamlessly

Recently, I came across a website that has an interesting feature where new content is loaded automatically while scrolling, seamlessly appending to the existing page. What's more fascinating is that not only does the content change, but the URL also ...

create a JavaScript array variable for posting items

My goal is to use this javascript to make four posts for the 'var msg' array. However, it currently posts 'encodeURIComponent(msg[i])' four times instead. How can I resolve this issue? var msg = ['one', 'two& ...

The call stack limit has been exceeded due to the combination of Node, Express, Angular, and Angular-route

Embarking on a new SPA journey, my tech stack includes: Back-end: NodeJS + Express Front-end: Angular + Angular-route. Twitter Bootstrap Underscore Having followed many tutorials with similar stacks, my project files are structured as follows: pac ...

Pressing the Enter key does not initiate a redirect on the page

Hey there! I've set up a text field where users need to input a password in order to download a PDF file. If the password is correct, they are directed to the URL of the PDF file. However, if the password is wrong, they are redirected to a page called ...

What is the best way to access a specific attribute of an HTML element?

Within my ng-repeat loop, I have set a custom attribute like this: <div ng-repeat="item in itemsList" stepType="{{item.stepType}}"> {{item.itemValue}} </div> The possible values for item.stepType are 'task' or 'action ...

Creating a new row with a dropdown list upon clicking a button

I want to include a Textbox and dropdown list in a new row every time I click a button. However, I seem to be having trouble with this process. Can someone assist me in solving this issue? Thank you in advance. HTML <table> <tr> ...

Exploring the latest upgrades in React 18 with a focus on TypeScript integration

I am currently working on a complex TypeScript project with React and recently made the decision to upgrade to the new version of React 18. After running the following commands: npm install react@18 npm install react-dom@18 npm install @types/react-dom@18 ...

Issue with JQueryUI Dialog auto width not accounting for vertical scrollbar

My JQueryUI Dialog has the width property set to 'auto'. Everything functions properly except in situations where the content exceeds the height of the dialog: A vertical scrollbar appears, but it disrupts the layout of the content within the dia ...

Can radio buttons be tested using Postman in conjunction with PHP?

I need to enhance my API code to allow users to input text and select one of three options using a radio button. How can I modify my API to include this feature, and what is the best way to test it using Postman? <?php $DBhost = " ...

What is the best way to ensure a table is responsive while maintaining a fixed header? This would involve the table scrolling when it reaches the maximum viewpoint, while also keeping

Can anyone help me create a responsive table with a fixed header that scrolls when it reaches the maximum viewpoint without scrolling the entire page? I've tried using box-sizing: border-box; and overflow-x:scroll; but it didn't work. Any suggest ...

Problem with OnClick function in Firefox

I have implemented the following code in an external JavaScript file: $( document ).ready(function() { var elem='<img class="imgload" src="/common/images/spinLoader/transperent.png">'; $('.imgchange').append(elem); }); $(func ...

Troubleshooting: Issues with AngularJS $route.reload() functionality

I have an angular app and I'm attempting to refresh the page. I've tried using $route.reload() as recommended in multiple posts, but I can't seem to get it to work (Chrome is showing me an error). Here's my controller: var app = angula ...

Transforming the JSON body request from Postman into a Jmeter body request

const today = new Date(); const time = today.getTime(); pm.environment.set('time', time); let eventArray = []; for(let i = 1; i <= 50; i++) { let t = time + (i * 1000); eventArray.push({ "eid": i, "time": t }); } con ...