中文字幕在线观看,亚洲а∨天堂久久精品9966,亚洲成a人片在线观看你懂的,亚洲av成人片无码网站,亚洲国产精品无码久久久五月天

用原生JS對AJAX做簡單封裝

2018-07-20    來源:open-open

容器云強(qiáng)勢上線!快速搭建集群,上萬Linux鏡像隨意使用

首先,我們需要xhr對象。這對我們來說不難,封裝成一個函數(shù)。

var createAjax = function() { var xhr = null; try { //IE系列瀏覽器 xhr = new ActiveXObject("microsoft.xmlhttp");
    } catch (e1) { try { //非IE瀏覽器 xhr = new XMLHttpRequest();
        } catch (e2) { window.alert("您的瀏覽器不支持ajax,請更換!");
        }
    } return xhr;
}; 

然后,我們來寫核心函數(shù)。

var ajax = function(conf) { // 初始化 //type參數(shù),可選 var type = conf.type; //url參數(shù),必填  var url = conf.url; //data參數(shù)可選,只有在post請求時需要 var data = conf.data; //datatype參數(shù)可選  var dataType = conf.dataType; //回調(diào)函數(shù)可選 var success = conf.success; if (type == null){ //type參數(shù)可選,默認(rèn)為get type = "get";
    } if (dataType == null){ //dataType參數(shù)可選,默認(rèn)為text dataType = "text";
    } // 創(chuàng)建ajax引擎對象 var xhr = createAjax(); // 打開 xhr.open(type, url, true); // 發(fā)送 if (type == "GET" || type == "get") {
        xhr.send(null);
    } else if (type == "POST" || type == "post") {
        xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
        xhr.send(data);
    }
    xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { if(dataType == "text"||dataType=="TEXT") { if (success != null){ //普通文本 success(xhr.responseText);
                }
            }else if(dataType=="xml"||dataType=="XML") { if (success != null){ //接收xml文檔  success(xhr.responseXML);
                }  
            }else if(dataType=="json"||dataType=="JSON") { if (success != null){ //將json字符串轉(zhuǎn)換為js對象  success(eval("("+xhr.responseText+")"));
                }
            }
        }
    };
}; 

最后,說明一下此函數(shù)的用法。

 ajax({ type:"post",
        url:"test.jsp",
        data:"name=dipoo&info=good",
        dataType:"json",
        success:function(data){ alert(data.name); } }); 

標(biāo)簽:

版權(quán)申明:本站文章部分自網(wǎng)絡(luò),如有侵權(quán),請聯(lián)系:west999com@outlook.com
特別注意:本站所有轉(zhuǎn)載文章言論不代表本站觀點!
本站所提供的圖片等素材,版權(quán)歸原作者所有,如需使用,請與原作者聯(lián)系。

上一篇:網(wǎng)頁右下方彈出提示框

下一篇:java加密解密類