Retrieving JSON Data from URLs in JavaScript
To access JSON data from a URL in JavaScript, you can employ various methods. One approach is to use jQuery's .getJSON() function:
$.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20yahoo.finance.quotes%20WHERE%20symbol%3D%27WRC%27&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback', function(data) { // JSON result in `data` variable });
This function retrieves and parses the JSON response asynchronously, providing the results in the data parameter of the callback function.
For a purely JavaScript-based solution, you can utilize the fetch() API:
fetch('http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20yahoo.finance.quotes%20WHERE%20symbol%3D%27WRC%27&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys') .then(response => response.json()) .then(data => { // JSON result in `data` object });
In this method, the fetch() request returns a Promise, which, when resolved, contains the JSON response. Using .then(), you can extract the JSON data and perform any necessary operations.
The above is the detailed content of How to Retrieve JSON Data from URLs in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!