ajax.js
function ajax(url) {
return new Promise((resolve, rejected) => {
let xhr = new XMLHttpRequest();
xhr.open("get", url, true);
xhr.send();
xhr.onload = function () {
if (xhr.status == 200) {
resolve(JSON.stringify(this.responseText));
}
}
xhr.onerror = function () {
rejected(xhr.status);
}
})
}
html页面
<script>
var url = "weather.php";
ajax(url).then(value => {
console.log(JSON.parse(value));
}, reason => {
console.log("请求失败"+reason);
})
</script>
Promise使用要点:
then是对前一个返回的Promise对象的状态进行处理。
对于then可以使用多种不同形式来封装一个Promise对象。
如果想要对promise的rejected实现统一的处理,可以在最末端添加catch来进行一致错误处理。