封装ajax


// http.js

const Ajaxs = (method, url, data, success) => {
  let ajax = new XMLHttpRequest()

  if (method.toLocaleLowerCase() === 'get') {
    if (data) {
      ajax.open(method, url + '?' + data, true)
    } else {
      ajax.open(method, url, true)
    }
    ajax.send()
  } else {
    ajax.open(method, url, true)
    ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
    if (data) {
      ajax.send(data)
    } else {
      ajax.send()
    }
  }

  ajax.onreadystatechange = () => {
    if (ajax.readyState === 4 && ajax.status === 200) {
      success(ajax.responseText)
    }
  }
}
<script src="./http.js"></script>
<script>
  
 /*   左侧为同步,右侧为异步,同步先执行,log s  为udefined
  *   解决此问题只需再多传一个回调,在回调里log,此时就不是同步了
  */  
 //  let s = Ajaxs('post', './3.json', '继而')
 //  console.log('s',s); // s undefined

  Ajaxs('post', './3.json', '666', res => {
    console.log('res---->',res) 
      // {
      //  "name":"Eric",
      //  "hobby":"read"
      //  }
  })
  
</script>

3.json

{
  "name":"Eric",
  "hobby":"read"
}

文章作者: KarlFranz
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 reprint policy. If reproduced, please indicate source KarlFranz !
评论
  目录