最新文章專(zhuān)題視頻專(zhuān)題問(wèn)答1問(wèn)答10問(wèn)答100問(wèn)答1000問(wèn)答2000關(guān)鍵字專(zhuān)題1關(guān)鍵字專(zhuān)題50關(guān)鍵字專(zhuān)題500關(guān)鍵字專(zhuān)題1500TAG最新視頻文章推薦1 推薦3 推薦5 推薦7 推薦9 推薦11 推薦13 推薦15 推薦17 推薦19 推薦21 推薦23 推薦25 推薦27 推薦29 推薦31 推薦33 推薦35 推薦37視頻文章20視頻文章30視頻文章40視頻文章50視頻文章60 視頻文章70視頻文章80視頻文章90視頻文章100視頻文章120視頻文章140 視頻2關(guān)鍵字專(zhuān)題關(guān)鍵字專(zhuān)題tag2tag3文章專(zhuān)題文章專(zhuān)題2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章專(zhuān)題3
問(wèn)答文章1 問(wèn)答文章501 問(wèn)答文章1001 問(wèn)答文章1501 問(wèn)答文章2001 問(wèn)答文章2501 問(wèn)答文章3001 問(wèn)答文章3501 問(wèn)答文章4001 問(wèn)答文章4501 問(wèn)答文章5001 問(wèn)答文章5501 問(wèn)答文章6001 問(wèn)答文章6501 問(wèn)答文章7001 問(wèn)答文章7501 問(wèn)答文章8001 問(wèn)答文章8501 問(wèn)答文章9001 問(wèn)答文章9501
當(dāng)前位置: 首頁(yè) - 科技 - 知識(shí)百科 - 正文

javascript Ajax 類(lèi)實(shí)現(xiàn)代碼

來(lái)源:懂視網(wǎng) 責(zé)編:小采 時(shí)間:2020-11-27 22:52:36
文檔

javascript Ajax 類(lèi)實(shí)現(xiàn)代碼

javascript Ajax 類(lèi)實(shí)現(xiàn)代碼:與現(xiàn)在那些Ajax框架比較,優(yōu)劣之處?看完再說(shuō)吧: 1、Ajax.js 代碼如下:/* AJAX v1.4 HJF 2009-7-5 */ function AjaxDO(){ this.HttpRequest = null; this.openMethod = null; //HTTP請(qǐng)求的方法,為Get、Post 或者
推薦度:
導(dǎo)讀javascript Ajax 類(lèi)實(shí)現(xiàn)代碼:與現(xiàn)在那些Ajax框架比較,優(yōu)劣之處?看完再說(shuō)吧: 1、Ajax.js 代碼如下:/* AJAX v1.4 HJF 2009-7-5 */ function AjaxDO(){ this.HttpRequest = null; this.openMethod = null; //HTTP請(qǐng)求的方法,為Get、Post 或者

與現(xiàn)在那些Ajax框架比較,優(yōu)劣之處?看完再說(shuō)吧:
1、Ajax.js
代碼如下:
/*
    AJAX v1.4
    HJF 2009-7-5
*/
function AjaxDO(){

    this.HttpRequest = null;

    this.openMethod = null; //HTTP請(qǐng)求的方法,為Get、Post 或者Head

    this.openURL = null; //是目標(biāo)URL?;诎踩紤],這個(gè)URL 只能是同網(wǎng)域的,否則會(huì)提示“沒(méi)有權(quán)限”的錯(cuò)誤。

    this.openAsync = null; //是指定在等待服務(wù)器返回信息的時(shí)間內(nèi)是否繼續(xù)執(zhí)行下面的代碼。如果為False,則不會(huì)繼續(xù)執(zhí)行,直到服務(wù)器返回信息。默認(rèn)為T(mén)rue。

    this.ProcessRequestFunction = function(_HttpRequest) {return;} //處理返回信息的函數(shù)入口

    this.ProcessRequestParam = null; //處理訪問(wèn)信息時(shí)的附加參數(shù)

    this.LoadingImg = null; //正在載入的圖片,一般為.gif動(dòng)畫(huà)

    //初始化HttpRequest
    this.InitHttpRequest = function(){
        var http;

    //    try {
    //        http = new ActiveXObject("Msxml2.XMLHTTP");
    //    } catch(e) {
    //        try {
    //            http = new ActiveXObject("Microsoft.XMLHTTP");
    //        } catch(e) {
    //            http = false;
    //        }
    //    }

        try    {
            if(window.ActiveXObject){
                for(var i=5; i; i--){
                    try{
                        if(i==2){
                            http = new ActiveXObject("Microsoft.XMLHTTP");
                        }else{
                            http = new ActiveXObject( "Msxml2.XMLHTTP." + i + ".0" );
                        }
                        break;
                    }catch(e){
                        //alert(i);
                        http = false;
                    }
                }
            }else if(window.XMLHttpRequest){
                http = new XMLHttpRequest();
                if(http.overrideMimeType){
                    http.overrideMimeType("text/xml");
                }
            }
        }catch(e){
            http = false;
        }

        if(!http){
            Alert("不能創(chuàng)建XMLHttpRequest對(duì)象實(shí)例");
            return http;
        }

        this.HttpRequest = http;
        return http;
    }

    //檢測(cè) this.HttpRequest
    this.checkHttpRequest = function(){
        if(!this.HttpRequest){
            return this.InitHttpRequest();
        }
        return this.HttpRequest;
    }

    //修改MIME類(lèi)別
    //http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //如果要傳文件或者Post 內(nèi)容給服務(wù)器
    //http.setRequestHeader("Content-Type","text/xml");
    //http.setRequestHeader("Content-Type","gb2312");
    this.setRequestHeader = function(mime){
        if(!this.checkHttpRequest()){
            return false;
        }
        try{
            this.HttpRequest.setRequestHeader("Content-Type", mime);
            return true;
        }catch(e){
            if(e instanceof Error){
                Alert("修改MIME類(lèi)別錯(cuò)誤");
                return false;
            }
        }
    }

    //設(shè)置狀態(tài)改變的事件觸發(fā)器
    this.setOnReadyStateChange = function(funHandle, Param){
        if(!this.checkHttpRequest()){
            return false;
        }
        this.ProcessRequestFunction = funHandle;
        this.ProcessRequestParam = Param;
        return true;
    }

    this.setLoadingImg = function(ImgID){
        this.LoadingImg = ImgID;
    }

    //建立HTTP連接
    //open("method","URL"[,asyncFlag[,"userName"[, "password"]]])
    this.Open = function(method, url, async, username, psw){
        if(!this.checkHttpRequest()){
            return false;
        }
        this.openMethod = method;
        this.openURL = url;
        this.openAsync = async;
        if((this.openMethod==null) || ((this.openMethod.toUpperCase()!="GET")&&(this.openMethod.toUpperCase()!="POST")&&(this.openMethod.toUpperCase()!="HEAD"))){
            Alert("請(qǐng)指定HTTP請(qǐng)求的方法,為Get、Post 或者Head");
            return false;
        }
        if((this.openURL==null)||(this.openURL=="")){
            Alert("請(qǐng)指定目標(biāo)URL");
            return false;
        }
        try{
            this.HttpRequest.open(this.openMethod, this.openURL, this.openAsync, username, psw);
        }catch(e){
            if(e instanceof Error){
                Alert("無(wú)法建立HTTP連接");
                return false;
            }
        }

        if(this.openMethod.toUpperCase()=="POST"){
            if(!this.setRequestHeader("application/x-www-form-urlencoded")){
                Alert("修改MIME類(lèi)別失敗");
                return false;
            }
        }

        if(this.openAsync){ //異步模式,程序繼續(xù)執(zhí)行
            if(this.ProcessRequestFunction==null){
                Alert("請(qǐng)指定處理返回信息的函數(shù)");
                return false;
            }
            var _http_request_ajax = this.HttpRequest;
            var _this_ajax = this;
            this.HttpRequest.onreadystatechange = function(){
                if(_http_request_ajax.readyState==4) {
                    if(_http_request_ajax.status==200) {
                        _this_ajax.ProcessRequestFunction(_http_request_ajax, _this_ajax.ProcessRequestParam, _this_ajax.LoadingImg);
                    }else{
                        Alert("您所請(qǐng)求的頁(yè)面有異常。");
                        return false;
                    }
                }
            }
        }

        if(this.LoadingImg!=null){
            funShow(this.LoadingImg);
        }

        return true;
    }

    //向服務(wù)器發(fā)出HTTP請(qǐng)求
    //格式:name=value&anothername=othervalue&so=on
    this.Send = function(idata){
        if(!this.checkHttpRequest()){
            return false;
        }
        var data = null;
        if(this.openMethod.toUpperCase()=="POST"){
            data = funEscapeAll(idata);
        }
        try{
            this.HttpRequest.send(data);
            return true;
        }catch(e){
            if(e instanceof Error){
                Alert("向服務(wù)器發(fā)出HTTP請(qǐng)求失敗");
                return false;
            }
        }
    }

    //處理服務(wù)器返回的信息
    this.getResponseText = function(type){
        if(!this.checkHttpRequest()){
            return false;
        }
        if(this.HttpRequest.readyState==4) {
            if(this.HttpRequest.status==200) {
                if((type!=null) && (type.toUpperCase()=="XML")){
                    return this.HttpRequest.responseXML;
                }
                return this.HttpRequest.responseText;
            }else{
                Alert("您所請(qǐng)求的頁(yè)面有異常。");
                return false;
            }
        }
    }

    //停止當(dāng)前請(qǐng)求
    this.abort = function(){
        if(!this.checkHttpRequest()){
            return false;
        }

        if(this.LoadingImg!=null){
            funHide(this.LoadingImg);
        }

        if(this.HttpRequest.readyState>0 && this.HttpRequest.readyState<4){
            this.HttpRequest.abort();
        }
    }

}

//=====================================================================================
//公共函數(shù)
//=====================================================================================
function $(_obj){
    var o;
    if (typeof(_obj)!="string")
        return _obj;
    else{
        try{
            document.all;
            try{
                o=document.all(_obj);
            }catch(e){
                return null;
            }
        }catch(ee){
            try{
                o=document.getElementById(_obj);
            }catch(e){
                return null;
            }
        }
        return o;
    }
}

function funEscapeAll(str){
    var t = "&";
    var s = str.split(t);
    if(s.length<=0)    return str;
    for(var i=0; i<s.length; i++){
        s[i] = funEscapeOne(s[i]);
    }
    return s.join(t);
}

function funEscapeOne(str){
    var i = str.indexOf("=");
    if(i==-1) return str;
    var t = URLEncode(str.substr(i+1));
    return str.substring(0, i+1)+t;
}

function URLEncode(str){
    return encodeURIComponent(str);
/*    
    return escape(str).replace(/\+/g, "%2B").
                replace(/\"/g,"%22").
                 replace(/\'/g, "%27").
                     replace(/\//g,"%2F");
*/
}

function funEscapeXML(content) {
if (content == undefined)
return "";
if (!content.length || !content.charAt)
content = new String(content);
var result = "";
var length = content.length;
for (var i = 0; i < length; i++) {
var ch = content.charAt(i);
switch (ch) {
case '&':
result += "&";
break;
case '<':
result += "<";
break;
case '>':
result += ">";
break;
case '"':
result += """;
break;
case '\'':
result += "'";
break;
default:
result += ch;
}
}
return result;
}

function funShow(_obj){
    if(typeof(_obj)=="object")
        _obj.style.visibility = "inherit";
    else
        $(_obj).style.visibility = "inherit";
}

function funHide(_obj){
    if(typeof(_obj)=="object")
        _obj.style.visibility = "hidden";
    else
        $(_obj).style.visibility = "hidden";
}

function Alert(str){
    alert(str);
    //window.status = str;
}

/*

使用例子:

function processRequest(http_request, _val, _loading_img){
    if(http_request.responseXML.documentElement){
        //alert(decodeURIComponent(http_request.responseXML.documentElement.xml));
    }else{
        //alert(decodeURIComponent(http_request.responseText));
    }
    alert(_val);
    funHide(_loading_img);
}

1、GET
    var ajax = new AjaxDO();

    ajax.setLoadingImg(_loading_img);
    ajax.setOnReadyStateChange(processRequest, _val);
    ajax.Open("GET", url, true); //異步模式,程序繼續(xù)執(zhí)行
    ajax.Send("");

    ajax.Open("GET", url, false); //非異步模式,程序等待
    ajax.Send("");
    var xml_doc = ajax.getResponseText("XML");
    var text_doc = ajax.getResponseText("TEXT");

2、POST
    var ajax = new AjaxDO();

    ajax.setLoadingImg(_loading_img);
    ajax.setOnReadyStateChange(processRequest, _val);
    ajax.Open("POST", url, true); //異步模式,程序繼續(xù)執(zhí)行
    ajax.Send(data);

    ajax.Open("POST", url, false); //非異步模式,程序等待
    ajax.Send(data);
    var xml_doc = ajax.getResponseText("XML");
    var text_doc = ajax.getResponseText("TEXT");

    
注,客戶端發(fā)送帶有中文或HTML腳本的信息時(shí),發(fā)送的信息必須調(diào)用:encodeURIComponent函數(shù),例如:
var data = encodeURIComponent($('message').value);
實(shí)際是調(diào)用了兩次,Ajax類(lèi)內(nèi)部又調(diào)用一次。

服務(wù)端(Java版)需要做下轉(zhuǎn)碼:
String message = request.getParameter("message");
message = URLDecoder.decode(message, "UTF-8");

*/

注,客戶端發(fā)送帶有中文或HTML腳本的信息時(shí),發(fā)送的信息必須調(diào)用:encodeURIComponent函數(shù),例如:
var data = encodeURIComponent($('message').value);
實(shí)際是調(diào)用了兩次,Ajax類(lèi)內(nèi)部又調(diào)用一次。

服務(wù)端(Java版)需要做下轉(zhuǎn)碼:

String message = request.getParameter("message");
message = URLDecoder.decode(message, "UTF-8");
2、Demo.html
代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>Ajax類(lèi)</title>
<script src="Ajax.js" src="Ajax.js"></script>

<style type="text/css"><!--
#Layer1 {
    position:absolute;
    left:670px;
    top:11px;
    width:15px;
    height:15px;
    z-index:10000;
    background-color:#FF0000;
    font-size:13;
    border:none;
    visibility:hidden;
}
--></style><style type="text/css" bogus="1">#Layer1 {
    position:absolute;
    left:670px;
    top:11px;
    width:15px;
    height:15px;
    z-index:10000;
    background-color:#FF0000;
    font-size:13;
    border:none;
    visibility:hidden;
}</style>
</head>

<body>
<div id="Layer1"><img src="indicator_flower.gif" src="indicator_flower.gif" width="15" /></div>
<script type="text/javascript" language="javascript"><!--
function processRequest(http_request, _val, _loading_img){
    alert(http_request.responseXML.documentElement.xml);
    //alert(http_request.responseText);
    funHide(_loading_img);
}
// --></script>
<script type="text/javascript" language="javascript"><!--
var url = "http://www.w3schools.com/xml/simple.xml";
var data = "";

var ajax = new AjaxDO();

function btnAjax1(){
    //var ajax = new AjaxDO();
    //ajax.InitHttpRequest();
    ajax.abort();

    ajax.setLoadingImg(document.getElementById("Layer1"));
    ajax.setOnReadyStateChange(processRequest);
    ajax.Open("GET", url, true); //異步模式,程序繼續(xù)執(zhí)行
    ajax.Send("");
}

function btnAjax2(){
    //var ajax = new AjaxDO();
    //ajax.InitHttpRequest();
    ajax.abort();

    ajax.Open("GET", url, false); //非異步模式,程序等待
    ajax.Send("");
    alert(ajax.getResponseText("XML").documentElement.xml);
    alert(ajax.getResponseText("TEXT"));
}
// --></script>
<button onclick="btnAjax1()">異步模式</button>
<button onclick="btnAjax2()">非異步模式</button>
</body>
</html>

3、圖片

聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com

文檔

javascript Ajax 類(lèi)實(shí)現(xiàn)代碼

javascript Ajax 類(lèi)實(shí)現(xiàn)代碼:與現(xiàn)在那些Ajax框架比較,優(yōu)劣之處?看完再說(shuō)吧: 1、Ajax.js 代碼如下:/* AJAX v1.4 HJF 2009-7-5 */ function AjaxDO(){ this.HttpRequest = null; this.openMethod = null; //HTTP請(qǐng)求的方法,為Get、Post 或者
推薦度:
標(biāo)簽: 實(shí)現(xiàn) js 代碼
  • 熱門(mén)焦點(diǎn)

最新推薦

猜你喜歡

熱門(mén)推薦

專(zhuān)題
Top