0%

723_promise_ajax封装练习

<script>
      // 封装一个函数sendAJAX发送GET请求,参数为url,放回结果为Promise对象
      function sendAJAX(url) {
        return new Promise((resolve, reject) => {
          const xhr = new XMLHttpRequest();
          xhr.responseType = "json";
          xhr.open("GET", url);
          xhr.send();
          //处理结果
          xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
              //判断成功
              if (xhr.status >= 200 && xhr.status < 300) {
                //成功的结果
                resolve(xhr.response);
              }
              //失败的结果
              reject(xhr.status);
            }
          };
        });
      }

      sendAJAX("http://api.apiopen.top/getJoke").then(
        (value) => {
          console.log(value);
        },
        (reason) => {
          console.warn(reason);
        }
      );
    </script>