ajax
XMLHttpRequest基本用法
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(httpRequest.readyState===4){
if(httpRequest.status===200){
var data = JSON.parse(httpRequest.response);
}
}
}
httpRequest.open('GET','https://api.github.com/users/ruanyf',true);
httpRequest.setRequestHeader("Content-Type","application/json");
httpRequest.send(null);
XMLHttpRequest封装
/**
* @description:
* @param {
* method:方法
* data: 参数
* type: 返回数据类型
* success: 响应成功后的会调
* error: 响应失败后的会调
* } option
* @return {*}
*/
function request(option) {
if(Object.prototype.toString.call(option) !== '[object, Object]') return undefined;
option.method = option.method ? option.method.toUpperCase() : 'GET';
option.data = option.data || {};
option.type = option.type || 'json';
var formData = [];
for(key in option.data) {
formData.push(''.concat(key, '=', option.data[key]))
}
option.data = formData.join('&')
if(option.method === 'GET' && formData.lenght > 0) {
option.url += location.search.length === 0 ? ''.concat('?', option.data) : ''.concat('&', option.data);
}
var xhr = new XMLHttpRequest();
xhr.responseType = option.type;
xhr.withCredentials = false; //指示是否应使用Cookie或授权标头等凭据进行跨站点访问控制请求。
// 处理请求回调
xhr.onreadystatechange = function() {
if(xhr.readyState === 4) {
if(xhr.status === 200) {
if(option.success && typeof option.success === 'function') {
option.success(xhr.response)
}
} else {
if(option.error && typeof option.error === 'function') {
option.error(new Error(xhr.statusText))
}
}
}
}
xhr.open(option.method, option.url, true); // true 代表是异步请求
// 如果是 POST 请求,需要设置请求头
if (option.method === 'POST') {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
}
// 发送请求
xhr.send(option.method === 'POST' ? option.data : null);
}
readyState状态
readyState | 描述 |
---|---|
0 | 还没有调用send()方法 |
1 | 已调用send()方法,正在发送请求 |
2 | send()方法执行完成,已经接收到全部响应内容 |
3 | 正在解析响应内容 |
4 | 响应内容解析完成,可以在客户端调用了 |
fetch的基本运用
fetch('https://xxx.com/api/user')
.then(res => res.json())
.then(result => { console.log(result) })
.catch(err => { console.log(err) })
fetch('https://xxx.com/api/user',{
method: 'POST',
headers: {},
data: {},
})
fetch以不同格式解析body
解析方法 | 方法描述 |
---|---|
response.text() | 读取 response,并以文本形式返回 response |
response.json() | 将 response 解析为 JSON 格式 |
response.formData() | 以 FormData 对象(在 下一章 有解释)的形式返回 response |
response.blob() | 以 Blob(具有类型的二进制数据)形式返回 response |
response.arrayBuffer() | 以 ArrayBuffer(低级别的二进制数据)形式返回 response |
- XMLHttpRequest基本用法
- XMLHttpRequest封装
- fetch的基本运用