练习
This commit is contained in:
86
teaching/jwl/课件/es6/promise.html
Normal file
86
teaching/jwl/课件/es6/promise.html
Normal file
@@ -0,0 +1,86 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Document</title>
|
||||
<script>
|
||||
console.log("创建proimise之前")
|
||||
var promiseobj=new Promise((resolve,reject)=>{
|
||||
console.log("创建promise")
|
||||
if (this.readyState !== 4) {
|
||||
return;
|
||||
}
|
||||
if (this.status === 200) {
|
||||
cosnole.log("mysuccess")
|
||||
resolve(this.response);
|
||||
} else {
|
||||
console.log("myerror")
|
||||
reject(new Error(this.statusText));
|
||||
}
|
||||
})
|
||||
promiseobj.then(()=>{
|
||||
console.log("success")
|
||||
|
||||
})
|
||||
console.log("promise成功之后")
|
||||
|
||||
|
||||
// readyState
|
||||
// 用promise封装ajax
|
||||
const getJSON = function(url) {
|
||||
const promise = new Promise(function(resolve, reject){
|
||||
const handler = function() {
|
||||
console.log(this.readyState)
|
||||
console.log(this.status)
|
||||
if (this.readyState !== 4) {
|
||||
return;
|
||||
}
|
||||
if (this.status === 200) {
|
||||
resolve(this.response);
|
||||
} else {
|
||||
reject(new Error(this.statusText));
|
||||
}
|
||||
};
|
||||
const client = new XMLHttpRequest();
|
||||
client.open("GET", url);
|
||||
client.onreadystatechange = handler;
|
||||
client.responseType = "json";
|
||||
client.setRequestHeader("Accept", "application/json");
|
||||
client.send();
|
||||
|
||||
});
|
||||
|
||||
return promise;
|
||||
};
|
||||
|
||||
|
||||
// readystate 的五种状态
|
||||
// 0 - (未初始化)还没有调用send()方法
|
||||
// 1 - (载入)已调用send()方法,正在发送请求
|
||||
// 2 - (载入完成)send()方法执行完成,已经接收到全部响应内容
|
||||
// 3 - (交互)正在解析响应内容
|
||||
// 4 - (完成)响应内容解析完成,可以在客户端调用了
|
||||
|
||||
|
||||
|
||||
getJSON("/posts.json").then(function(json) {
|
||||
console.log('Contents: ' + json);
|
||||
}, function(error) {
|
||||
console.error('出错了', error);
|
||||
});
|
||||
|
||||
async function login(){
|
||||
http("./login.php").then((res)=>{
|
||||
console.log(res)
|
||||
})
|
||||
var res=http("./login.php")
|
||||
}
|
||||
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user