我正在尝试创建一个小型的天气预报网站。向accuWeather发送获取JSON的请求时,无法获得响应。我已经检查了几次请求,它正常工作。有人能指出我的代码中有什么问题吗?这样我就可以修复它了。此外,如果您回答,是否可以使用Javascript而不是使用JQuery链接:
这是我学习javascript的项目。apiKey也是公开的。
<html>
<head>
<meta charset="utf-8"/>
<title>getting</title>
<script>
function start(){
//console.log("asdasd");
var requestURL = "http://dataservice.accuweather.com/locations/v1/cities/search?apikey=BfZGgoA9OaaSy7oyAReezmDFngUe2Lek&q=Annandale&language=en-us&details=true" ;
var request = new XMLHttpRequest();
console.log(request);
request.open('GET', requestURL);
//console.log(request.response);
}
window.addEventListener("load",start,false);
</script>
</head>
<body>
<div id="loading"></div>
</body>
</html>
如果有任何帮助,我将不胜感激。
发布于 2018-05-29 02:37:07
有几件事。首先,您需要实际使用send()
发送请求。其次,如果你正在做一个异步请求,你需要添加一个监听器来处理响应:
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200)
console.log(request.response);
};
request.send(null);
如果您不希望将其设为异步的,则可以始终将false
作为第二个参数传递给您的open()
调用,但强烈建议您这样做,因为这将是一个阻塞调用。
请随意阅读更多关于XMLHttpRequests here for more options的内容
这是一个working example
发布于 2018-05-29 02:36:58
您应该尝试这样做:
<html>
<head>
<meta charset="utf-8"/>
<title>getting</title>
<script>
function start(){
//console.log("asdasd");
var requestURL = "http://dataservice.accuweather.com/locations/v1/cities/search?apikey=BfZGgoA9OaaSy7oyAReezmDFngUe2Lek&q=Annandale&language=en-us&details=true" ;
var request = new XMLHttpRequest();
console.log(request);
request.open('GET', requestURL);
request.send();
//console.log(request.response);
}
window.addEventListener("load",start,false);
</script>
</head>
<body>
<div id="loading"></div>
</body>
</html>
或者类似这样的东西:
<html>
<head>
<meta charset="utf-8"/>
<title>getting</title>
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Action to be performed when the document is read;
}
};
xhttp.open("GET", "http://dataservice.accuweather.com/locations/v1/cities/search?apikey=BfZGgoA9OaaSy7oyAReezmDFngUe2Lek&q=Annandale&language=en-us&details=true", true);
xhttp.send();
window.addEventListener("load",start,false);
</script>
</head>
<body>
<div id="loading"></div>
</body>
</html>
https://stackoverflow.com/questions/50571818
复制相似问题