您的位置:首页 > 编程语言

ajax 原生代码 已封装get,post,封装 附加 Promise 如何请求数据 详解

2018-10-15 11:08 731 查看
function ajax(method, url, data) {
var xhr = null;
if (XMLHttpRequest) {
xhr = new XMLHttpRequest()
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP")
}
if (method == "get") {
xhr.open(method, url + "?" + data, true);
xhr.send();
} else {
xhr.open(method, url, true);
xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
xhr.send(data);
}
return new Promise((sucee, fail)=> {
xhr.onreadystatechange = ()=> {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
sucee(xhr.responseText)
} else {
fail(xhr.status)
}
}
}
})
}
<script>
tada =  ajax("get","josn/josn1.js","")

tada.then(function(date){

console.log(date);

})

</script>
阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: