1.如何使用promise封装原生ajax
get
function getRequest(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open('GET', url, true)
xhr.onreadystatechange = function () {
if(xhr.readyState!=4)return
if (xhr.readyState === 4 && xhr.status === 200) {
resolve(this.responseText, xhr)
} else {
reject(xhr.responseText);
}
}
xhr.send(null)
})
}
post
function postJSON(url, data) {
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest()
xhr.open("POST", url, true)
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState != 4) return
if (xhr.readyState === 4 && xhr.status === 200) {
resolve(xhr.responseText)
} else {
reject(xhr.responseText)
}
}
xhr.send(JSON.stringify(data))
})
}
2.如何使用promise封装$ajax()
let ajax=function(url, param, type = 'GET'){
const promise = new Promise(function(resolve, reject){
$.ajax({
type: type,
url: url,
data: param,
dataType: 'json',
success(res) {
resolve(res)
},
error(res) {
reject('响应错误')
// reject(res.statusText)
}
})
})
return promise
}
ajax('http://wh.xhd.cn/api/content/list.jspx',{id: 1}).then(res=>{
console.log(res)
})
3.fetch的使用
Fetch API 提供了一个 JavaScript 接口,用于访问和操纵 HTTP 管道的一些具体部分,例如请求和响应。它还提供了一个全局
fetch() 方法,该方法提供了一种简单,合理的方式来跨网络异步获取资源。 这种功能以前是使用 XMLHttpRequest
实现的。Fetch 提供了一个更理想的替代方案,可以很容易地被其他技术使用
1.fetch请求数据
fetch(url, {
// get 请求可以省略不写 默认的是GET
method: 'get'
})
.then(function(data) {
return data.text();
}).then(function(data) {
console.log(data)
});
2.Response对象
fetch的then中返回的不是一个字面量对象,而是一个Response对象的实例,返回的实例可用以下方法,分别处理数据
arrayBuffer() 获取ArrayBuffer格式的promise对象
blob() 获取Bolb格式的promise对象
json() -获取字符串对象
text()获取json的promise对象
formData() 获取formData格式的promise对象
详见fetch文档