zoukankan      html  css  js  c++  java
  • Ajax fetch axios的区别与优缺点

    Ajax  fetch axios的区别与优缺点

    原生ajax:

    var xhr=new XMLHttpRequest();
    xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
    xhr.open('post','test.php');
    xhr.send('name=test&age=18');
    xhr.onreadystatechange=function(){
      if(xhr.readySate==4&&xhr.status==200){
        console.log(xhr.responseText);
      }
    }

    jqueryAjax

    var btn=document.getElementById('btn');
    btn.onclick=function(){
      ajax({
        type:'post',
        url:'test.php',
        data:"name=test&&pwd=123456",
        success:function(data){
          console.log(data);
        }
      });
    }

    fetch

    fetch('http://www.mozotech.cn/bangbang/index/user/login', {
        method: 'post',
        headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: new URLSearchParams([
            ["username", "Lan"],["password", "123456"]
        ]).toString()
    })
    .then(res => {
        console.log(res);
        return res.text();
    })
    .then(data => {
        console.log(data);
    })

    axios

    axios.post({
      url:'test.php',
      data:{name:'test',age:18},
    })
    .then(res=>{console.log(res)})
    .catch(error=>{console.log(error)});
    
    同时发起多个请求:
    
    function getUserAccount(){
       return axios.get('user/123456')
    }
    function getUserPermissions(){
       return axios.get('user/123456/permission')
    }
    
    axios.all([getUserAccount(),getUserPermission()])
    .then(axios.spread((acct,perms)=>{
    }))

    对比 

    1 几种方式的对比

    ajax:

    优点:局部更新,原生支持

    缺点:可能破坏浏览器后退功能,嵌套回调

    jqueryAjax:

    在原生ajax的基础上进行封装,支持jsonp

    fetch:

    优点:解决回调地狱

    缺点:APIA偏低层,需要封装,默认不带cookie,需要手动添加;浏览器支持情况不是很友好,需要第三方polyfill

    axios的特点:

    支持浏览器和node.js

    支持promise

    能拦截请求和响应

    能转换请求和相应数据

    能取消请求

    自动转换json数据

    浏览器端支持防止CSRF(跨站请求伪造)

     将axios异步请求同步处理:

    async getInfo(){
    
      try{
    
        let data=await axios.get('test.php');
    
        console.log(data);
    
      }catch(err){
    
        console.log(err)
    
      }
    
    }
  • 相关阅读:
    构造函数和析构函数
    关联[2]
    关联模型[1]
    auth 权限控制
    多语言设置
    文件上传
    验证码
    图像处理
    Session 与 Cookie
    控制器[3]
  • 原文地址:https://www.cnblogs.com/xiaofenguo/p/12837465.html
Copyright © 2011-2022 走看看