webveuje/teaching/jwl/课件/es6/promise.html
2021-04-29 17:16:40 +08:00

86 lines
2.5 KiB
HTML
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!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>