ajax和axios使用和方法

心里最崇拜的那个人,不必变成那个人,而是用那个人的精神和方法,去变成你自己
----本文来自拉勾大前端

Ajax

  • AJAX就是浏览器提供的一套API,可以通过javascript调用,从而实现代码控制请求与响应,通过javascript进行网络编程
    // jQuery 中的 Ajax 方法
    $.ajax({
      url: "https://jsonplaceholder.typicode.com/users",
      type: "GET",
      dataType: "json",
      data: {"id": 1},
      success: function (data) {
        // 使用请求成功的数据
        console.log(data);
      }
    })
    

ajax请求

  • 创建XMLHttpRequest类型的对象
  • 准备发送,打开与网址之间的连接
  • 执行发送动作
  • 指定xhr状态变化事件处理函数
    // 1.创建一个 XMLHttpRequest 类型的对象  --- 相当于打开了一个浏览器
    var xhr = new XMLHttpRequest();
    // 2.打开一个与网址之间的连接  --- 相当于在地址栏输入网址
    xhr.open("GET","https://jsonplaceholder.typicode.com/users");
    // 3.通过连接发送一次请求 --- 相当于点击回车或者超链接
    xhr.send(null);
    // 4.指定 xhr 状态变化事件处理函数   --- 相当于处理网页呈现后的操作
    xhr.onreadystatechange = function () {
      // 通过判断 xhr 的 readyState ,确定此次请求是否完成
      if (this.readyState === 4) {
        console.log(this.responseText)
      }
    }
    

原生Ajax详解

  • readyState属性:readyState属性返回一个XMLHttpRequest代理当前所处的状态,由于readystatechange事件是在xhr对象状态变化时触发
    • 0:代理XHR被创建,但尚未调用open()方法
    • 1:open()方法已经被调用,建立了连接
    • 2:send()方法已经被调用,并且已经可以获取状态行和响应头
    • 3:响应体下载中,responseText属性可能已经包含部分数据
    • 4: 响应体下载完成,可以直接使用responseText
// 1.创建一个 XMLHttpRequest 类型的对象 
var xhr = null;
// 兼容写法
if (window.XMLHttpRequest) {
  // 标准浏览器
  xhr = new XMLHttpRequest();
} else {
  // IE 6 浏览器
  xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
// 2.open() 方法开启请求
// xhr.open("GET","https://jsonplaceholder.typicode.com/users?id=1");
xhr.open("POST","https://jsonplaceholder.typicode.com/users");
// 设置请求头
// 一般 get 方法不需要设置,而 post 方法必须设置
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
// 3.send() 方法发送一次请求
// 如果是 get 方法请求,不需要再 send 中传参数,它如果想传参数,直接写在网址上
// xhr.send(null);
xhr.send("name=harry&age=19");

xhr.onreadystatechange = function () {
  // 通过判断 xhr 的 readyState ,确定此次请求是否完成
  if (this.readyState === 4) {
    console.log(this.responseText)
  }
}

同步和异步

  • xhr.open()方法第三个参数要求传入一个boolean值,作用就是设置此次请求时否采用异步方式执行
  • 默认为true异步,如果需要同步执行可以通过传递false实现
  • 如果采用同步方式执行,则代码会卡死在xhr.send()
  • 建议:为了让这个事件可靠,在发送请求send()之前,一定是先注册readystatechange

数据格式

  • XML数据类型(淘汰)
  • JSON数据类型
    • JSON数据不需要存到变量中
    • 结束不需要写分号
    • JSON数据中属性名必须加引号
  • 使用json对象的parse方法可以将字符串转换成对象格式
    //可以通过这种方法将获得的json数据转换成字符串
    var strObj = JSON.parse(str);
    console.log(strObj.name)
    

json-server

  • 方便我们自己上传json数据,需要在本地搭建一个临时服务器
  • json-server是一个Node模块,运行Express服务器,你可以指定一个json文件作为api的数据源
  • 网址:https://github.com/typicode/json-server
  • 命令行输入:json-server --watch 文件名.json

原生Ajax--GET请求

var xhr =new XMLHttpRequest();
//发送get请求
//在open中传参
xhr.open("GET","http://localhost:3000/posts?id=1");
xhr.send(null);
xhr.onreadystatechange = function(){
  if(this.readyState === 4){
    console.log(this.responseText);
  }
}

原生Ajax--POST请求

  • post请求过程中,都是采用请求体承载需要提交的数据
  • 需要设置请求头中的content-type,以便于服务端接收数据
  • 需要提交到服务端的数据可以通过send方法的参数传递
    var xhr = new XMLHttpRequest();
    //POST请求
    xhr.open("POST","http://localhost:3000/posts");
    //post要设置请求头
    xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    //向服务器添加数据
    // xhr.send("age=19")
    xhr.send(JSON.stringify({
      "name": "dxa",
      "age": 18,
      "class": "lagou"
    }))
    // xhr.send({"age":19})
    xhr.onreadystatechange = function(){
      if(this.readyState === 4){
        console.log(this.responseText)
      }
    }
    

封装AJAX函数

// 封装自己的 Ajax 函数
/**
  * 参数1:{string}    method  请求方法
  * 参数2:{string}    url     请求地址
  * 参数3:{Object}    params  请求参数
  * 参数4:{function}  done    请求完成后执行的回调函数
*/ 
function ajax(method, url, params, done) {
  // 统一将方法中的字母转大写,便于后面判断
  method = method.toUpperCase();
  // 书写 IE 6 的兼容
  var xhr = window.XMLHttpRequest  
  ? new XMLHttpRequest() 
  : new ActiveXObject("Microsoft.XMLHTTP");
  // 将对象格式的参数转为 urlencoded的格式
  var pairs = [];
  for (var k in params) {
    pairs.push(k + "=" + params[k]);
  }
  var str = pairs.join("&");
  // 判断是否是 get 方法,需要更改 url 的值
  if (method === "GET") {
    url += "?" + str;
  }
  // 创建打开一个连接
  xhr.open(method, url);
  var data = null;
  // 如果是 post 方法,需要设置请求头,还有请求体
  if (method === "POST") {
    xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    data = str;
  }
  xhr.send(data);
  // 执行回调函数
  xhr.onreadystatechange = function () {
    if (this.readyState !== 4) return;
    // 执行外部传进来的回调函数即可
    // 需要用到响应体
    done(JSON.parse(this.responseText));
  }
}
// 调用函数
ajax("GET", "http://localhost:3000/users",{"id": 1},function (data) {
  console.log(data);
});
ajax("POST", "http://localhost:3000/users",{"name": "john","age": 19,"class": 2},function (data) {
  console.log(data);
});

jQuery中ajax

$.ajax()

  • url: 请求地址
  • type: 请求方法,默认为get
  • dataType: 服务端响应数据类型
  • contentType: 请求体内容类型,默认application/x-www-form-urlencoded
  • data: 需要传递到服务端的数据
  • timeout: 请求超时时间
  • beforeSend: 请求发起之前触发
  • success: 请求成功之后触发
  • error: 请求失败触发,比如请求地址错误
  • complete: 请求完成触发
    $.ajax({
      url: "http://localhost:3000/posts",
      type: "get",
      dataType: "json",
      // data: {"id": 1},
      beforeSend: function(xhr){
        console.log("before send");
      },
      success: function(data){
        console.log(data);
      },
      complete: function(xhr){
        console.log(xhr.status)
      }
    })
    

$.get()

  • get请求的快捷方式
  • $.get(url,data,callback)
    $.get("http://localhost:3000/posts",{},function(data){
      console.log(data)
    })
    

$.post()

  • post请求的快捷方式,添加数据的方式
 $.post("http://localhost:3000/posts",{"name": "dxa"},function(data){
   console.log(data)
 })

其他数据类型

// put 请求,更改数据
$.ajax({
  url: "http://localhost:3000/comments/4",
  type: "put",
  dataType: "json",
  data: {"content": "good", "postId": 2},
  success: function (data) {
    console.log(data)
  }
})
// delete 请求,删除数据
$.ajax({
  url: "http://localhost:3000/comments/5",
  type: "delete",
  success: function (data) {
    console.log(data)
  }
})

Axios

  • Axios是目前应用最为广泛的AJAX封装库
  • 线上文件:https://unpkg.com/axios/dist/axios.min.js
  • 参考文档:http://axios-js.com/zh-cn/docs/

Axios API

  • 可以通过向axios()传递相关配置来创建请求
  • axios(config) config为对象格式的配置选项
  • axios(url,config) config可选

常用配置选项

  • url 用于请求服务器的URL
  • method 创建请求时使用的方法
  • baseURL 传递相对URL前缀,将自动加在url前面
  • headers 即将被发送的自定义请求头
  • params 即将与请求一起发送的URL参数
  • data 作为请求主体被发送的数据
  • timeout 请求超时的毫秒数
  • responseType 表示服务器响应的数据类型,默认json
    axios({
      url: "/posts",
      method: "get",
      baseURL: "http://localhost:3000",
      params: {
        id: 1
      }
    }).then(function(res){
      console.log(res.data)
    })
    

全局默认配置

  • 可以指定将被用在各个请求的配置默认项
  • 利用axios.defaults修改全局变量
    // 全局配置默认值
    axios.defaults.baseURL = "http://localhost:3000";
    

onload/onprogress

  • xhr.onload事件:只在请求完成时触发
  • xhr.onprogress事件: 只在请求进行中触发
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:3000/posts");
xhr.onload = function () {
  console.log("load",this.readyState)
}
xhr.onprogress = function (e) {
  console.log("progress",this.readyState)
  // 在周期性请求过程中,接收到的数据的个数
  console.log(e.loaded);
  // 接收数据的总个数
  console.log(e.total);
}
xhr.send(null);

response属性

  • 以对象的形式表述响应体,其类型取决于responseType的值
  • responseType要在调用open()初始化请求之后

你可能感兴趣的:(ajax和axios使用和方法)