簡體   English   中英

使用 AJAX 從 JSON(外部 URL http://)中提取數據?

[英]Extracting data from a JSON (External URL http://) using AJAX?

如何從 JSON 文件中提取數據? 這不是我的 URL,它歸外部資源所有(ABS,是一家生產天氣信息的公司)。 此天氣數據已放入 JSON 文件中。 為什么我不能訪問它的信息? 並存儲它

 <html> <head> <meta content="text/html; charset = ISO-8859-1" http-equiv="content-type"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script type="application/javascript"> function loadJSON() { var data_file = "http://reg.bom.gov.au/fwo/IDW60901/IDW60901.94610.json"; var http_request = new XMLHttpRequest(); http_request.onreadystatechange = function() { if (http_request.readyState == 4) { // Javascript function JSON.parse to parse JSON data var jsonObj = JSON.parse(http_request.responseText); // jsonObj variable now contains the data structure and can // be accessed as jsonObj.name and jsonObj.country. document.getElementById("name").innerHTML = jsonObj.name; document.getElementById("air_temp").innerHTML = jsonObj.air_temp; } } http_request.open("GET", data_file, true); http_request.send(); } </script> <title>The Current Weather</title> </head> <body> <h1>Weather in Perth City</h1> <div class="central"> <button type="button" onclick="loadJSON()">Show Information </button> </div> </body> </html>

您可以使用某些站點發送跨源請求,例如:

https://cors-anywhere.herokuapp.com/<url>

 <html> <head> <meta content="text/html; charset = ISO-8859-1" http-equiv="content-type"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script type="application/javascript"> function loadJSON() { var data_file = "https://cors-anywhere.herokuapp.com/http://reg.bom.gov.au/fwo/IDW60901/IDW60901.94610.json"; var http_request = new XMLHttpRequest(); http_request.onreadystatechange = function() { if (http_request.readyState == 4) { // Javascript function JSON.parse to parse JSON data var jsonObj = JSON.parse(http_request.responseText); // jsonObj variable now contains the data structure and can // be accessed as jsonObj.name and jsonObj.country. document.getElementById("name").innerHTML = jsonObj.observations.data[0].name; document.getElementById("air_temp").innerHTML = jsonObj.observations.data[0].air_temp; } } http_request.open("GET", data_file, true); http_request.setRequestHeader("X-Requested-With","XMLHttpRequest"); http_request.send(); } </script> <title>The Current Weather</title> </head> <body> <h1>Weather in Perth City</h1> <div class="central"> <button type="button" onclick="loadJSON()">Show Information </button> </div> <div id ="name"></div> <div id="air_temp"></div> </body> </html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM