美文网首页
实现原生的AJAX请求

实现原生的AJAX请求

作者: my木子 | 来源:发表于2021-10-28 16:16 被阅读0次
    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);
    });

相关文章

网友评论

      本文标题:实现原生的AJAX请求

      本文链接:https://www.haomeiwen.com/subject/asuvaltx.html