美文网首页
ajax异步回调

ajax异步回调

作者: 逆流成河wsy | 来源:发表于2017-11-13 13:46 被阅读16次
           function ajax(url, fnSucc, fnFail) {
                var oAjax = new XMLHttpRequest();
                oAjax.open('GET', url, true);
                oAjax.send();
                oAjax.onload = function () {
                    if (oAjax.readyState == 4 && oAjax.status == 200) {
                        fnSucc(oAjax.responseText)
                    } else {
                        fnFail(oAjax.status);
                    }
                };
            }
            window.onload = function () {
                let oBtn = document.getElementById('btn1');
    
                oBtn.onclick = function () {
                    ajax('a.txt', function (str) {
                        alert(str);
                    }, function (str) {
                        alert(str);
                    });
                };
            };
    

    promise异步封装例子

        function ajax(url, fnSucc, fnFail) {
                var oAjax = new XMLHttpRequest();
                oAjax.open('GET', url, true);
                oAjax.send();
                oAjax.onload = function () {
                    if (oAjax.readyState == 4 && oAjax.status == 200) {
                        fnSucc(oAjax.responseText)
                    } else {
                        fnFail(oAjax.status);
                    }
                };
            }
            window.onload = function () {
                let oBtn = document.getElementById('btn1');
                let oBox = document.getElementById('box1');
    
                oBtn.onclick = function () {
                    let p1 = new Promise(function (resolve, reject) {
                        ajax('a.txt', function (str) {
                            resolve(str);
                        }, function (str) {
                            reject(str);
                        });
                    });
    
                    p1.then(function (str) {
                        oBox.innerHTML = str;
                    }, function (str) {
                        oBox.innerHTML = str;
                    });
    
                };
            };
    

    相关文章

      网友评论

          本文标题:ajax异步回调

          本文链接:https://www.haomeiwen.com/subject/ktkzmxtx.html