使用 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. 显示一个加载状态,如果响应正确,设置loading为false
  2. 显示加载状态,如果响应出错,则将加载设置为 false,将错误设置为 true。
,

您将不得不等待 xhr.readyState 成为 4 与侦听器。 应该是这样的:

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