jQuery 中的 AJAX
jQuery 中有一套专门针对 AJAX 的封装,功能十分完善。
参考网址:jQuery 参考手册 - Ajax (w3school.com.cn)
$.ajax() 方法(传入对象格式参数)
常用选项参数 | 说明 |
---|---|
url | 请求地址 |
type | 请求方法,默认为 get
|
dataType | 服务端响应数据类型 |
contentType | 请求体内容类型,默认 application/x-www-form-urlencoded
|
data | 需要传递到服务端的数据 如果 GET 则通过 URL 传递,如果 POST 则通过请求体传递 |
timeout | 请求超时时间 |
beforeSend | (回调函数)请求发起之前触发 |
success | (回调函数)请求成功之后触发(响应状态码 200) |
error | (回调函数)请求失败触发 |
complete | (回调函数)请求完成触发(不管成功与否) |
快捷请求方法
$.get(url, data, callback)
:GET 请求快捷方法
$.post(url, data, callback)
:POST 请求快捷方法
url
:请求地址;data
:需要传递到服务器的数据;callback
:回调函数
更改与删除请求
- put 请求,更改数据
// 以下为拉勾教育课件内代码
$.ajax({
// comments为接口,接口之后要传入所需要修改的数据 id
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 封装库。
Axios 网址:axios中文网 (axios-js.com)
Axios 库
地址:https://unpkg.com/axios/dist/axios.min.js 在 html 中使用 script 标签引入。
Axios API
可以通过向 axios() 传递相关配置来创建请求
-
axios(config)
config为对象格式的配置选项
// 以下为拉勾教育课件内代码
axios({
url: "/comments",
method: "post",
baseURL: "http://localhost:3000",
headers: {
"Content-Type": "application/json"
},
timeout: 1000,
data: {
"postId": 3,
"content": "better"
}
})
-
axios(url, config)
config 可选
axios("http://localhost:3000/posts", {
params: {
id: 1
}
})
常用配置项 | 说明 |
---|---|
url | 用于请求的服务器 URL,必需 |
method | 创建请求时使用的方法 |
baseURL | 传递相对 URL 前缀,将自动加在 url 前面 |
headers | 即将被发送的自定义请求头 |
params | 即将与请求一起发送的 URL 参数 |
data | 作为请求主体被发送的数据 |
timeout | 指定请求超时的毫秒数(0 表示无超时时间) |
responseType | 表示服务器响应的数据类型,默认 “json” |
then 和 catch
axios()
.then(function (response) {
// 正常请求的响应信息对象 response
})
.catch(function (error) {
//捕获错误
})
全局配置默认值
可以指定将被用在各个请求的配置默认值,比如:
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
拦截器
拦截器可以在请求或响应被 then 或 catch 处理前拦截它们。
可以通过添加请求拦截器在发现请求之前更改全局的默认配置:
// 使用拦截器,对请求进行拦截处理
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.get(url[, config])
获取数据 -
axios.post(url[, data[, config]])
添加数据 -
axios.delete(url[, config])
删除数据 -
axios.put(url[, data[, config]])
更改数据
// get 请求
axios.get("http://localhost:3000/users?id=2")
axios.get("http://localhost:3000/users",{
params: {
id: 3
}
})
// post 请求
axios.post("http://localhost:3000/users",{
"name": "nancy",
"age": 19,
"class": 2
})