Peomise+Ajax
function creatXHR() {
var xhr;
if(window.XMLHttpRequest){
xhr = new window.XMLHttpRequest();
}else if(window.ActiveXObject('MicrosoftXMLHTTP')){
xhr = new ActiveXObject();
}else{
console.log('your brower can not support XMLHttpRequest');
}
return xhr;
}
function getAjax(url) {
var xhr = creatXHR();
return new Promise(function (resolve,reject) {
xhr.onreadystatechange = function () {
if(xhr.readyState == 4){
if(200 <= xhr.status <= 304){
resolve(xhr.responseText);
}else{
reject('error reject');
}
}
};
xhr.open('GET',url);
xhr.send(null);
});
}
getAjax('data.js').then(function (msg) {
console.log(msg);
});
async+await+promise+ajax
<!DOCTYPE html>
<html lang="en">
<head>
<Meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div class="scriptText"></div>
<script> var url = 'http://o4j806krb.qnssl.com/public/index.min.aeb155e1.min.js'; var xhr = new XMLHttpRequest(); var text; function getScript(url) { return new Promise(function (resolve,reject) { xhr.onreadystatechange = function () { if(xhr.readyState === 4 && xhr.status === 200){ text = xhr.responseText; resolve(xhr.responseText); } }; xhr.open('GET',url); xhr.send(null); }); } var processMessage = function(url) { var ele = document.getElementsByClassName('scriptText')[0]; getScript(url); ele.innerHTML = text; }; var processMessageAsync = async function(url) { var ele = document.getElementsByClassName('scriptText')[0]; await getScript(url); ele.innerHTML = text; }; processMessage(url); setTimeout(function () { processMessageAsync(url); },3000); </script>
</body>
</html>