Promise實現ajax


利用Promise實現ajax

 

GET

    function getAjax(url) {
        return new Promise((resolved,rejected)=>{
            //創建ajax對象
            let ajax = new XMLHttpRequest();
            //配置參數
            ajax.open('get',url,true)
            //發送請求
            ajax.send();
            //請求成功之后
            ajax.onload = function () {
                if(this.status === 200){
                    console.log(ajax.responseText)
                    resolved(ajax.responseText);
                }else{
                    rejected();
                }

            }
        })
    }
View Code
getAjax(url).then().catch()

 

POST

    function postAjax(url,param) {
        return new Promise((resolved,rejected)=>{
            //創建ajax對象
            let ajax = new XMLHttpRequest();
            //配置參數
            ajax.open('post',url,true);

            //設置請求頭,表示我傳遞的參數的類型
            xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            //發送請求,並將數據傳遞過去
            ajax.send(JSON.stringify(data));

            //請求成功之后
            ajax.onload = function () {
                if(this.status === 200){
                    console.log(ajax.responseText)
                    resolved(ajax.responseText);
                }else{
                    rejected();
                }

            }
        })
    }
View Code
getAjax(url,param).then().catch()

 

GET \POST合並

    function myAjax(type,url,params) {
        return new Promise((resolved,rejected)=>{

            //創建ajax對象
            let ajax;
            //注意,不要根據瀏覽器的navigator.userAgent來檢測瀏覽器是否支持某個JavaScript特性,一是因為這個字符串本身可以偽造,二是通過IE版本判斷JavaScript特性將非常復雜。
            if (window.XMLHttpRequest) {
                ajax = new XMLHttpRequest();
            } else {
                ajax = new ActiveXObject('Microsoft.XMLHTTP');
            }


            if(type == 'get' || type == ''){//get
                //配置參數
                ajax.open('get',url,true)
                //發送請求
                ajax.send();
            }else if(type == 'post'){//post
                //配置參數
                ajax.open('post',url,true);
                //設置請求頭,表示我傳遞的參數的類型
                xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                //發送請求,並將數據傳遞過去
                ajax.send(JSON.stringify(data));
            }

            //請求成功之后
            request.onreadystatechange = function (){
                if (request.readyState === 4){
                    if(this.status === 200){
                        console.log(ajax.responseText)
                        resolved(ajax.responseText);
                    }else{
                        rejected();
                    }
                }
            }

        })
    }
View Code
    getAjax('get').then().catch()
    getAjax('post',param).then().catch()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM