Ajax常用库:jQuery和Axios库

1,917 阅读2分钟

jQuery中的Ajax方法

参考: www.w3school.com.cn/jquery/jque…
先在html代码中进行jQuery引用,没下载的可参考jQuery基础进行下载引用:

<script src="js/jquery-1.12.4.min.js"></script>

$.ajax()方法

常用选项参数介绍:

  • url:请求地址
  • type:请求方法,默认为、get
  • dataType:服务端响应数据类型
  • contentType:请求体内容类型,默认、application/x-www-form-urlencoded
  • data:需要传递到服务端的数据,如果GET则通过URL传递,如果POST则通过请求体传递
  • timeout:请求超时时间
  • beforeSend:请求发起之前触发
  • success:请求成功之后触发(响应状态码200)
  • error:请求失败触发
  • complete:请求完成触发(不管成功与否)
// $.ajax()
// 参数是一个 配置的对象
$.ajax({
  url: "http://localhost:3000/posts",
  type: "get",
  dataType: "json",
  data: {"id": 2},
  beforeSend: function (xhr) {
    console.log("before send");
  },
  success: function (data) {
    console.log(data);
  },
  error: function (xhr) {
    console.log(xhr);
  },
  complete: function (xhr) {
    console.log(xhr);
  }
});

$.get()请求

// 发送 get 请求
// $.ajax({
//   url: "http://localhost:3000/comments",
//   type: "get",
//   dataType: "json",
//   data: {"id": 2},
//   success: function (data) {
//     console.log(data);
//   }
// })
// 化简后的方法直接发送 get 请求
$.get("http://localhost:3000/comments", {"id": 1}, function (data) {
  console.log(data);
})

$.post()请求

POST请求快捷方法: post(url,data,callback)

// 发送 post 请求
// $.ajax({
//   url: "http://localhost:3000/comments",
//   type: "post",
//   dataType: "json",
//   data: {"postId": 2, "content": "bad"},
//   success: function (data) {
//     console.log(data);
//   }
// })
// $.post() 快捷方法发送请求
$.post("http://localhost:3000/comments", {"postId": 3, "content": "bad"},function (data) {
  console.log(data);
})

其他类型请求

  • put 更改
  • delete 删除
// 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)
  }
})

jQuery中的其他Ajax方法

其他方法可从 www.w3school.com.cn/jquery/jque… 学习

// ajaxSetup() 方法,设置默认的参数
$.ajaxSetup({
  url: "http://localhost:3000/users",
  type: "post"
})
// 发送 ajax请求
$.ajax({
  data: {"name": "polly", "age": 17, "class": 4}
})
$.ajax({
  data: {"name": "james", "age": 18, "class": 4}
})

Axios库

Axios是目前应用最为广泛的AJAX封装库。 其中文官网是: axios-js.com/

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
// 体会 get 请求
<script>
  // 体会 get 请求
  axios.get("http://localhost:3000/posts")
    .then(function (response) {
      console.log(response.data)
    })
    .catch(function (error) {
      console.log(error)
    })
</script>

Axios API

可以通过向axios()传递相关配置来创建请求:

  • axios(config): config为对象格式的配置选项
  • axios(url, config): config可选 常用配置项: | 配置项 | 作用 | |------|------------| | url | 常用,用于请求的服务器URL,必需 | | method | 常用,创建请求时使用的方法 | | baseURL | 传递相对URL前缀,将自动加在url前面 | | headers | 即将被发送的自定义请求头 | | params | 常用,即将与请求一起发送的URL参数 | | data | 常用,作为请求主体被发送的数据 | | timeout | 指定请求超时的毫秒数(0表示无超时时间) | | responseType | 表示服务器响应的数据类型,默认"json” |
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
  // axios 方法
  axios({
    url: "/comments",
    method: "post",
    baseURL: "http://localhost:3000",
    headers: {
      "Content-Type": "application/json"
    },
    timeout: 1000,
    data: {
      "postId": 3,
      "content": "better"
    }
  }).then(function (res) {
    console.log(res.data)
  }).catch(function (error) {
    console.log(error)
  })
</script>

全局配置默认值

可以指定将用在各个请求的配置默认值:

  • axios.defaults.baseURL = 'https://api.example.com';
  • axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
  • ...等等
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
  // 全局配置默认值
  axios.defaults.baseURL = "http://localhost:3000";
  // axios 方法
  axios({
    url: "/comments",
    method: "get"
  }).then(function (res) {
    console.log(res.data)
  }).catch(function (error) {
    console.log(error)
  })
</script>

axios方法的参数

axios(url, config): config可选,如果省略,其参数将以默认参数进行加载,比如method将为GET方法等。

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
  // axios 方法
  axios("http://localhost:3000/posts", {
    params: {
      id: 1
    }
  })
  .then(function (res) {
    console.log(res.data)
  })
  .catch(function (error) {
    console.log(error)
  })
</script>

axios拦截器

在请求或响应被then或catch处理前拦截它们。

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
  // 使用拦截器,对请求进行拦截处理
  axios.interceptors.request.use(function (config) {
    config.params = {
      id: 2
    }
    config.baseURL = "http://localhost:3000"
    return config
  })
  // 对响应进行拦截
  axios.interceptors.response.use(function (response) {
    return response.data;
  })
  // axios 方法    
  axios("/posts")
  .then(function (res) {
    console.log(res)
  })
  .catch(function (error) {
    console.log(error)
  });
  axios("/comments")
  .then(function (res) {
    console.log(res)
  })
  .catch(function (error) {
    console.log(error)
  })
</script>

快速请求方法get和post

  • axios.get(url[, config])
  • axios.post(url[, data[, config]])
  • axios.delete(url[, config])
  • axios.put(url[, data[, config]])
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
  // get 请求
  // 方法一
  // axios.get("http://localhost:3000/users?id=2")
  //   .then(function (res) {
  //     console.log(res.data)
  //   })
  // 方法二
  axios.get("http://localhost:3000/users",{
    params: {
      id: 3
    }
  })
    .then(function (res) {
      console.log(res.data)
    })
  // post 请求 ,添加数据
  axios.post("http://localhost:3000/users",{
    "name": "nancy",
    "age": 19,
    "class": 2
  })
  .then(function (res) {
    console.log(res.data)
  })
</script>

XHR2.0-onload和onprogress事件

HTML5中对HTMLHttpRequest类型进行了全面升级,变得更易用,更强大。

  • xhr.onload事件:只在请求完成时触发
  • xhr.onprogress事件:只在请求进行中触发
<script>
  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);
</script>

response 属性

  • response属性是以对象的形式表述响应体,其类型取决于responseType的值。你可以尝试设置responseType的值,以便通过特定的类型请求数据。
  • responseType要在调用open()初始化请求之后,在调用send()发送请求到服务器之前设置方可生效。
<script>
  var xhr = new XMLHttpRequest();
  xhr.open("GET", "http://localhost:3000/posts");
  xhr.responseType = "json";
  xhr.onload = function () {
    console.log(this.response);
  }    
  xhr.send(null);
</script>