用 promise 的方式实现 ajax
function ajax( type, url, data ) {
// new 一个 promise 对象
return new Promise( (resolve, reject) => {
var xmlHttp = new XMLHttpRequest(),
context = this,
urls = data ? url+'?' : url;
// 监听变化
xmlHttp.onreadystatechange = function() {
// 请求成功
if( xmlHttp.readyState === 4 && xmlHttp.status === 200 ) {
resolve( JSON.parse( xmlHttp.responseText ) )
}
}
// 如果是 get 方式请求并且需要穿参
if( type === 'GET' && data ) {
for( key in data ) {
urls += ( key + '=' + data[ key ] );
}
}
xmlHttp.open( type, urls, true );
xmlHttp.send( data )
})
}
// 测试
ajax( 'GET', './data.json', null)
.then(function(res) {
console.log(res);
})
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

上一篇: 手写 ajax 方法
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论