# ajax&axios&fetch

# ajax

  $.ajax({
    type:'POST',
    url:url,
    data:data,
    dataType:dataType,
    success:function(){},
    error:function(){}
  });
1
2
3
4
5
6
7
8
  • 缺点:
    • 是针对MVC的编程,不符合MVVM
    • 基于原生XHR开发,XHR的架构不清晰
    • JQ整个项目太大,单纯使用ajax要引入整个JQ不合理

# axios

  axios({
    method:'post',
    url:'/user/111',
    data:{
      name:'xxx'
    }
  }).then((response)=>{
    console.log(response)
  }).catch((error)=>{
    console.log(error);
  })
1
2
3
4
5
6
7
8
9
10
11
  • 优点:
    • 支持promise API
    • 自动转换JSON数据
    • 从node.js发出HTTP请求
    • 客户端支持防止CSRF/XSRF

# fetch

  fetch('/bar').then((response)=>{
    response.text()
  },(err)=>{
    console.log(err)
  })
1
2
3
4
5
  try{
    let response=await fetch('/bar');
    let data=response.json()
  } catch(e){
    console.log(e)
  }
1
2
3
4
5
6