实现原生的AJAX请求

2021-10-28  本文已影响0人  my木子
    const ajax = {
      get(url, fn) {
          const xhr = new XMLHttpRequest()
          xhr.open('GET', url, true)// 第三个参数异步与否
          xhr.onreadystatechange = function() {
              if (xhr.readyState === 4) {
                fn(JSON.parse(xhr.responseText));
              }
          }
          xhr.send()
      },
      post(url, data, fn) {
          const xhr = new XMLHttpRequest()
          xhr.open('POST', url, true)
          xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded')
          xhr.onreadystatechange = function () {
              if (xhr.readyState === 4) {
                fn(JSON.parse(xhr.responseText));
              }
          }
          xhr.send(data)
      }
    }
    ajax.get('https://api.apiopen.top/getJoke?page=1&count=2&type=video',(res)=>{
      console.log(res);
    });
上一篇 下一篇

猜你喜欢

热点阅读