如何从 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>
关于javascript - 从 JSON 中提取数据(外部 URL http ://) using AJAX?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60789219/