原生ajax

异步方式

const xhr = new XMLHttpRequest();

xhr.open('GET', 'data.json');       
xhr.addEventListener('load', () => {        //需要使用回调拿到数据
    console.log(xhr.responseText);
})
xhr.send();

status code

const xhr = new XMLHttpRequest();

xhr.open('GET', 'data.json');       
xhr.addEventListener('load', ()=>{          //增加对 status code 的判断 
    if(xhr.status >= 200 && xhr.status <300 || xhr.status === 304)    
        console.log(xhr.responseText);
    else 
        alert('请求失败')
})
xhr.send();

readyState

const xhr = new XMLHttpRequest();

xhr.open('GET', 'data.json');
xhr.onreadystatechange = () => {
  if(xhr.readyState === 4) {      // readyState === 4对应load事件
    if(xhr.status >= 200 && xhr.status <300 || xhr.status === 304)
      console.log(xhr.responseText);
    else
      alert('请求失败');    
  }
}
xhr.send();

post请求带参数

const xhr = new XMLHttpRequest();

xhr.open('POST', '/login', true);       //post请求
xhr.send('username=wang&pass=123');        //设置请求参数
xhr.addEventListener('load', ()=>{             
    if(xhr.status >= 200 && xhr.status <300 || xhr.status === 304) {
        const data = xhr.responseText;
        console.log(data);
    }
    else {
        alert('请求失败')
    }
})

get请求带参数

const xhr = new XMLHttpRequest();

xhr.open('GET', '/login?username=wang&pass=123', true);       //get请求,带参数  
xhr.send();

xhr.addEventListener('load', ()=>{             
    if(xhr.status >= 200 && xhr.status <300 || xhr.status === 304) {
        const data = xhr.responseText;
        console.log(data);
    }
    else {
        alert('请求失败')
    }
})

封装ajax

function ajax(opts){
  let url = opts.url
  const type = opts.type || 'GET'
  const dataType = opts.dataType || 'json'
  const data = opts.data || {}
  const onsuccess = opts.onsuccess || function(){}
  const onerror = opts.onerror || function(){}

  let dataStr = Object.entries(data).map(v => `${v[0]}=${v[1]}`).join('&')

  if(type === 'GET' && dataStr != '')
    url += '?' + dataStr

  const xhr = new XMLHttpRequest()
  xhr.open(type, url, true)

  xhr.addEventListener('load', ()=>{
    if(xhr.status >= 200 && xhr.status <300 || xhr.status ===304) {
      if(dataType === 'json')
        onsuccess(JSON.parse(xhr.responseText))
      else
        onsuccess(xhr.responseText)
    }
    else
      console.log('错误码' + xhr.status)
  })
  xhr.onerror = onerror

  if(type === 'GET')
    xhr.send()
  else
    xhr.send(dataStr)
}

ajax({
  url: '/data.json',
  dataType: 'text',
  data: {
      username: 'wang',
      pass: '123',
  },
  type: 'GET',
  onsuccess: data => console.log(data),
  onerror: () => console.log('fail'),
})
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 没有学Ajax之前,就在想这到底是一门什么技术,问自己什么是Ajax?Ajax有哪些重点概念?Ajax如何运用?听...
    张延伟阅读 2,100评论 0 8
  • AJAX: XMLHttpRequest是AJAX的基础 1.创建一个XMLHttpRequest对象: 2.用X...
    johe_jianshu阅读 1,625评论 0 4
  • AJAX 原生js操作ajax 1.创建XMLHttpRequest对象 var xhr = new XMLHtt...
    碧玉含香阅读 3,500评论 0 7
  • 关于晋商,中国的华尔街,曾经享誉全球。电影中处处渗透着晋商对票号的管理之道。 1.掌柜3年不得见自己的女人,不得养...
    隽芳Juanfang阅读 838评论 0 0

友情链接更多精彩内容