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)
    
      }
    
    }
  • 相关阅读:
    45 岁,还写代码吗?
    给你 8 个接私活的网站
    一文回顾 Java 入门知识(下)
    5 种前途迷茫的编程语言
    JVM 内存的结构模型、堆与堆栈原理、对象在内存中的结构
    mysql 索引是否能提高UPDATE,DELETE,INSERT 处理速度
    【诈尸】【游戏】多人联机游戏推荐
    250.统计同值子树
    366. 寻找二叉树的叶子节点
    156.上下翻转二叉树
  • 原文地址:https://www.cnblogs.com/xiaofenguo/p/12837465.html
Copyright © 2011-2022 走看看