gpt4 book ai didi

javascript - 从 JSON 中提取数据(外部 URL http ://) using AJAX?

转载 作者:行者123 更新时间:2023-12-02 21:23:48 25 4
gpt4 key购买 nike

如何从 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com