Promise+ajax && async+await+promise+ajax

前端之家收集整理的这篇文章主要介绍了Promise+ajax && async+await+promise+ajax前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Peomise+Ajax

//创建XHR对象
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);//await必须在async环境中 ele.innerHTML = text; }; processMessage(url);//这里测试不用async时的情况,页面显示undefined setTimeout(function () { processMessageAsync(url);//3s后页面显示获取到的内容 },3000); //上面ajax能跨域获取数据的原因是o4j806krb.qnssl.com服务器将其资源的CORS设置为acces-control-allow-origin为* </script>
</body>
</html>

猜你在找的Ajax相关文章