方法一:回调函数
<!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>查看物流</title>
</head>
<body>
<script>
//POST请求
function openPost(url, data,callback) {
let xhr = new XMLHttpRequest();
xhr.open("post", url);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify(data));
xhr.onload = function () {
var res = JSON.parse(xhr.response);
if (res.code == 2000) {
if(typeof(callback)=='function'){
callback(res)
}
console.log(res);
} else {
if(typeof(callback)=='function'){
callback('失败')
}
console.log("请求" + url + "失败");
}
};
}
var data = {
username: getCookie("username"),
sessionId: getCookie("sessionId"),
flag: this.flag,
id: parseInt(this.id),
};
var url = "/cgi-bin/software";
openPost(url, data,function(data){
console.log(data,'===123')
});
</script>
</body>
</html>
方法二
<!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>查看物流</title>
</head>
<body>
<script>
//POST请求
function openPost(url, data) {
return new Promise((reslove, reject) => {
let xhr = new XMLHttpRequest();
xhr.open("post", url);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify(data));
xhr.onload = function () {
var res = JSON.parse(xhr.response);
if (res.code == 2000) {
reslove(res)
console.log(res);
} else {
reject('失败')
console.log("请求" + url + "失败");
}
};
})
}
var data = {
username: getCookie("username"),
sessionId: getCookie("sessionId"),
flag: this.flag,
id: parseInt(this.id),
};
var url = "/cgi-bin/software";
openPost(url, data).then(res=>{
console.log(res)
}).catch(err=>{
console.log(err)
});
</script>
</body>
</html>