代码拉取完成,页面将自动刷新
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Promise</title>
<script>
//ES6中 Promise对象是一个构造函数,用来生成Promise
//它接收一个函数(function作为参数),这个参数function有两个参数,分别是resolve,reject
//promise是对原始ajax的封装,可以进行串行调用(维护多个异步请求)
//resolve的作用是 promise对象的状态从未完成到成功,成功后异步操作结果作为参数传递
//reject的作用是 promise对象的状态从未完成到失败,失败后异步操作结果作为参数传递
//then()方法分别指定resolve reject 的回到函数
//deferred就是jQuery中promise的实现
//then() done() 实现链式调用 区别是then()传递的方法有返回值,下一个链式调用该方法,done()不会再调用后面的then()
window.onload = function(){
var promise = new Promise(function(resolve,reject){});
promise.then(function(){});//成功
promise.catch(function(){});//失败
}
//jQuery 1.5.0之前版本返回的是XHR对象,1.5.0之后返回的是deferred对象
//封装的原生Promise
const getJSON = function(url,type, data) {
const promise = new Promise(function(resolve, reject){
const handler = function() {
if (this.readyState !== 4) {
return;
};
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error(this.statusText));
}
};
const client = new XMLHttpRequest();
client.open(type, url);
client.onreadystatechange = handler;
client.responseType = "json";
if(type =='get'){
client.send();
}else {
client.setRequestHeader("Content-Type", "application/json");
client.send(JSON.stringify(data));
}
});
return promise;
};
</script>
</head>
<body>
</body>
</html>
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。