使用Ajax完成前后端通信的一个小例子

23 阅读1分钟

readyStatus注意大小写

url接口地址不要写错

<script>
  const url = "https://api.vvhan.com/api/la.ji?lj=避孕套";
  const xhr = new XMLHttpRequest();

  xhr.onreadystatechange = () => {
  
    if (xhr.readyState !== 4) {
      return;
    }

    if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
      console.log("请求响应成功");
      console.log(xhr.responseText);
    }
  };

  xhr.open("get", url, true);
  xhr.send();
</script>