AjAX 步骤和对比fetch和axios

511 阅读5分钟

什么是ajax

AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。

AJAX 不是新的编程语言,而是一种使用现有标准的新方法。

AJAX 是与服务器交换数据并更新部分网页的艺术,在不重新加载整个页面的情况下。

ajax使用步骤

第一步,创建xmlhttprequest对象,

var xmlhttp =new XMLHttpRequest();

XMLHttpRequest对象用来和服务器交换数据。

var xhttp;
if (window.XMLHttpRequest) {
//现代主流浏览器
xhttp = new XMLHttpRequest();
} else {
// 针对浏览器,比如IE5或IE6
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

第二步,使用xmlhttprequest对象的open()和send()方法发送资源请求给服务器。

xmlhttp.open(method,url,async) method包括get

和post,url主要是文件或资源的路径,async参数为true(代表异步)或者false(代表同步)

xhttp.send();使用get方法发送请求到服务器。

xhttp.send(string);使用post方法发送请求到服务器。

post 发送请求什么时候能够使用呢?

(1)更新一个文件或者数据库的时候。

(2)发送大量数据到服务器,因为post请求没有字符限制。

(3)发送用户输入的加密数据。

get例子:

xhttp.open("GET", "ajax_info.txt", true);
xhttp.open("GET", "index.html", true);
xhttp.open("GET", "demo_get.asp?t=" + Math.random(), true);xhttp.send()

post例子

xhttp.open("POST", "demo_post.asp", true);
xhttp.send();

post表单数据需要使用xmlhttprequest对象的setRequestHeader方法增加一个HTTP头。

post表单例子

xhttp.open("POST", "ajax_test.aspx", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname=Henry&lname=Ford");

async=true 当服务器准备响应时将执行onreadystatechange函数。

xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "index.aspx", true);
xhttp.send();

asyn=false 则将不需要写onreadystatechange函数,直接在send后面写上执行代码。

xhttp.open("GET", "index.aspx", false);
xhttp.send();
document.getElementById("demo").innerHTML = xhttp.responseText;

第三步,使用xmlhttprequest对象的responseText或responseXML属性获得服务器的响应。

使用responseText属性得到服务器响应的字符串数据,使用responseXML属性得到服务器响应的XML数据。

document.getElementById("demo").innerHTML = xhttp.responseText;

第四步,onreadystatechange函数,当发送请求到服务器,我们想要服务器响应执行一些功能就需要使用onreadystatechange函数,每次xmlhttprequest对象的readyState发生改变都会触发onreadystatechange函数。

onreadystatechange属性存储一个当readyState发生改变时自动被调用的函数。 readyState属性,XMLHttpRequest对象的状态,改变从0到4,0代表请求未被初始化,1代表服务器连接成功,2请求被服务器接收,3处理请求,4请求完成并且响应准备。 status属性,200表示成功响应,404表示页面不存在。

在onreadystatechange事件中,服务器响应准备的时候发生,当readyState==4和status==200的时候服务器响应准备。

封装代码

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>Examples</title>
  <script>

    //将对象序列化
    function params(data) {
      var arg = [];
      for (var i in data) {
        arr.push(encodeURIComponent(i) + '=' + encodeURIComponent(data[i]));
      }
      return arr.join('&');
    }

    //封装ajax
    function ajax(obj) {
      //创建xhr对象;
      obj.xhr = new XMLHttpRequest();
      //后面随机数防止浏览器缓存
      obj.url = url + "?rand=" + Math.random();
      //序列化对象
      obj.data = params(obj.data);
      //当是get请求时
      if (obj.method = 'get') {
        //当前面没设置随机数时
        obj.url += obj.url.indexOf('?') == -1 ? '?' +obj.data : '&' + obj.data;
      }
      //异步调用
      if (obj.async == true) {
        //监听响应状态
        xhr.onreadystatechange = function() {
          if (xhr.readyState == 4) {
            callback();
          }
        };
      }
      //启动HTTP请求
      xhr.open(obj.method, obj.url, obj.aysnc);
      //当是post请求时
      if(obj.method === 'post') {
        //模仿表单提交
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        //发送HTTP请求-post
        xhr.send(obj.data);
      } else {
        //发送HTTP请求-get
        xhr.send(null);
      }
      //同步调用
      if (obj.async == false) {
        callback();
      }
      //回调函数传参
      function callback() {
        if (xhr.atatus == 200) {
          obj.success(xhr.responseText);
        } else {
          alert("失败,失败状态码:" + xhr.status);
        }
      }
    }

    document.addEventListener('click', function() {
      ajax({
        method: 'get',
        url: 'demo3.php',
        data: {
          'name' = 'Lee',
          'age' = 100
        },
        success: function(text) {
          alert(text);
        },
        async = true
      });
    }, false);
  </script>
</head>
<body>
    
</body>
</html>

promise封装ajax

 const getJSON = function (url) {
            const promise = new Promise(function (resolve, reject) {
                const handler = function () {
                    if (this.readyState !== 4) {
                        return;
                    }
                    if (this.status === 200) {
                        resolve(this.response);
                    } else {
                        reject(new Error(this.statusText));
                    }
                };
                const client = new XMLHttpRequest();
                client.open("GET", url);
                client.onreadystatechange = handler;
                client.responseType = "json";
                client.setRequestHeader("Accept", "application/json");
                client.send();

            });

            return promise;
        };

        getJSON("/posts.json").then(function (json) {
            console.log('Contents: ' + json);
        }, function (error) {
            console.error('出错了', error);
        });    

二、fetch

fetch 是全局量 window 的一个方法,它的主要特点有:

1、第一个参数是URL:

2、第二个是可选参数,可以控制不同配置的 init 对象

3、使用了 JavaScript Promises 来处理结果/回调:

// 链式处理,将异步变为类似单线程的写法: 高级用法.
fetch('/some/url').then(function(response) {
    return . //... 执行成功, 第1步...
}).then(function(returnedValue) {
    // ... 执行成功, 第2步...
}).catch(function(err) {
    // 中途任何地方出错...在此处理 :( 
});

从 fetch()返回的 Promise 将不会拒绝HTTP错误状态, 即使响应是一个 HTTP 404 或 500。相反,它会正常解决 (其中ok状态设置为false), 并且仅在网络故障时或任何阻止请求完成时,它才会拒绝。 可以做简单的封装

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response
  } else {
    var error = new Error(response.statusText)
    error.response = response
    throw error
  }
}

function parseJSON(response) {
  return response.json()
}

fetch('/users')
  .then(checkStatus)
  .then(parseJSON)
  .then(function(data) {
    console.log('request succeeded with JSON response', data)
  }).catch(function(error) {
    console.log('request failed', error)
  })

默认情况下, fetch在服务端不会发送或接收任何 cookies, 如果站点依赖于维护一个用户会话,则导致未经认证的请求(要发送 cookies,必须发送凭据头). 这一点也可以做一些处理: 如果想要在同域中自动发送cookie,加上 credentials 的 same-origin 选项

fetch(url, {
  credentials: ’same-origin'
})

same-origin值使得fetch处理Cookie与XMLHttpRequest类似。 否则,Cookie将不会被发送,导致这些请求不保留认证会话。

对于CORS请求,使用include值允许将凭据发送到其他域:

fetch(url, {
  credentials: 'include'
})

2.axios

axios({
    method: 'post',
    url: '/user/12345',
    data: {
        firstName: 'Fred',
        lastName: 'Flintstone'
    }
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});

优缺点:

从 node.js 创建 http 请求

支持 Promise API

客户端支持防止CSRF

提供了一些并发请求的接口(重要,方便了很多的操作)

为什么要用axios?

axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,它本身具有以下特征:

从浏览器中创建 XMLHttpRequest

从 node.js 发出 http 请求

支持 Promise API

拦截请求和响应

转换请求和响应数据

取消请求

自动转换JSON数据

客户端支持防止CSRF/XSRF