使用XML HTTP请求在Javascript中获取HTTP GET请求的错误



我是Javascript的新手。我正在尝试制作一个简单的提示网站,并尝试使用HTTP GET请求从该网站获取一个形容词:https://random-word-form.herokuapp.com/

然而,我总是收到一个糟糕的请求错误。我尝试了一个测试API,看了几个视频,并使用了与他们相同的代码,看看我是否可以解决我的问题,但仍然无法工作。

我们将不胜感激。

javascript代码如下:

let adjective; 
function buttonclick(method, url){
console.log("hi");
const xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.responseType = 'json';
xhr.send();
xhr.onload = function(){
if(xhr.status!=200){
alert('Error');
}
else {
alert('got ${xhr.response.length');
}
let responseData = xhr.response;
return responseData;
};
};
function getData(){
adjective = buttonclick('GET','https://random-word-form.herokuapp.com/random/adjective');
console.log(adjective);
};
getData();

这里有一个使用fetch方法的示例。

let loading = true
let error = false
function getData() {
const url = 'https://random-word-form.herokuapp.com/random/adjective'
fetch(url).then(res => {
return res.json()
}).then(res => {
console.log(res) // <- here is your data aka response
})
.catch(err => {
console.log(err);
error = true
})
.finally(() => {
loading = false
})
}
<button onclick="getData()">get adj</button>


请记住,如果您使用API,您应该处理所有可能的状态:loadingsuccesserror。有一些很好的文章描述了基础知识。

你至少应该做的是:

  1. 显示加载状态,如果响应正确,则将加载设置为false
  2. 显示加载状态,如果响应出现错误,则将loading设置为false,将error设置为true

您必须等待xhr.readyState为4,然后才能使用侦听器。应该是这样的:

xhr.onreadystatechange = function(){
if (xhr.readyState === 4){
// do Something 
}
};

最新更新