Home > Web Front-end > JS Tutorial > body text

How to Retrieve JSON Data from a URL in JavaScript?

Mary-Kate Olsen
Release: 2024-10-29 05:39:30
Original
701 people have browsed it

How to Retrieve JSON Data from a URL in JavaScript?

Retrieve JSON Data from URL in JavaScript

Understanding the Issue

The provided URL returns JSON data, but an attempt to retrieve it using readJsonFromUrl failed. The goal is to obtain a JavaScript object that represents the JSON response.

Solution using jQuery

One efficient method to retrieve JSON data in JavaScript is through the jQuery $.getJSON() function:

<code class="javascript">$.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20yahoo.finance.quotes%20WHERE%20symbol%3D%27WRC%27&amp;format=json&amp;diagnostics=true&amp;env=store://datatables.org/alltableswithkeys&amp;callback', function(data) {
    // Access the JSON data in the `data` variable
});</code>
Copy after login

Alternative Pure JavaScript Solution

If you prefer not to use jQuery, consider this pure JavaScript solution:

<code class="javascript">var request = new XMLHttpRequest();
request.open('GET', 'http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20yahoo.finance.quotes%20WHERE%20symbol%3D%27WRC%27&amp;format=json&amp;diagnostics=true&amp;env=store://datatables.org/alltableswithkeys&amp;callback');
request.onreadystatechange = function() {
    if (request.readyState == 4 && request.status == 200) {
        var data = JSON.parse(request.responseText);
        // Access the JSON data in the `data` variable
    }
};
request.send();</code>
Copy after login

The above is the detailed content of How to Retrieve JSON Data from a URL in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!