中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

javascript Ajax類的實現代碼

發布時間:2021-09-01 16:49:44 來源:億速云 閱讀:143 作者:chen 欄目:web開發

本篇內容主要講解“javascript Ajax類的實現代碼”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“javascript Ajax類的實現代碼”吧!

與現在那些Ajax框架比較,優劣之處?看完再說吧:
1、Ajax.js

復制代碼 代碼如下:


/*
    AJAX v1.4
    HJF 2009-7-5
*/
function AjaxDO(){

    this.HttpRequest = null;

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

    this.openURL = null; //是目標URL。基于安全考慮,這個URL 只能是同網域的,否則會提示“沒有權限”的錯誤。

    this.openAsync = null; //是指定在等待服務器返回信息的時間內是否繼續執行下面的代碼。如果為False,則不會繼續執行,直到服務器返回信息。默認為True。

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

    this.ProcessRequestParam = null; //處理訪問信息時的附加參數

    this.LoadingImg = null; //正在載入的圖片,一般為.gif動畫

    //初始化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("不能創建XMLHttpRequest對象實例");
            return http;
        }

        this.HttpRequest = http;
        return http;
    }

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

    //修改MIME類別
    //http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //如果要傳文件或者Post 內容給服務器
    //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類別錯誤");
                return false;
            }
        }
    }

    //設置狀態改變的事件觸發器
    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("請指定HTTP請求的方法,為Get、Post 或者Head");
            return false;
        }
        if((this.openURL==null)||(this.openURL=="")){
            Alert("請指定目標URL");
            return false;
        }
        try{
            this.HttpRequest.open(this.openMethod, this.openURL, this.openAsync, username, psw);
        }catch(e){
            if(e instanceof Error){
                Alert("無法建立HTTP連接");
                return false;
            }
        }

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

        if(this.openAsync){ //異步模式,程序繼續執行
            if(this.ProcessRequestFunction==null){
                Alert("請指定處理返回信息的函數");
                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("您所請求的頁面有異常。");
                        return false;
                    }
                }
            }
        }

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

        return true;
    }

    //向服務器發出HTTP請求
    //格式: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("向服務器發出HTTP請求失敗");
                return false;
            }
        }
    }

    //處理服務器返回的信息
    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("您所請求的頁面有異常。");
                return false;
            }
        }
    }

    //停止當前請求
    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();
        }
    }

}

//=====================================================================================
//公共函數
//=====================================================================================
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); //異步模式,程序繼續執行
    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); //異步模式,程序繼續執行
    ajax.Send(data);

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

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

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

*/


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

服務端(Java版)需要做下轉碼:

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類</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); //異步模式,程序繼續執行
    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、圖片

javascript Ajax類的實現代碼

到此,相信大家對“javascript Ajax類的實現代碼”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

淳化县| 廊坊市| 宜阳县| 博野县| 嵊泗县| 炎陵县| 嘉善县| 临江市| 武强县| 白水县| 宁津县| 抚宁县| 凭祥市| 霸州市| 云龙县| 阿拉善左旗| 郸城县| 华蓥市| 临城县| 恩平市| 青龙| 缙云县| 义马市| 潼关县| 手机| 乌恰县| 定西市| 岗巴县| 万宁市| 饶平县| 巴彦县| 扶余县| 莒南县| 阿拉善盟| 肥乡县| 灵川县| 淄博市| 靖江市| 锡林浩特市| 定兴县| 东海县|