search
HomeWeb Front-endJS TutorialJavaScript Ajax class example code

/*
    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(/\&#39;/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 &#39;&&#39;:
result += "&";
break;
case &#39;<&#39;:
result += "<";
break;
case &#39;>&#39;:
result += ">";
break;
case &#39;"&#39;:
result += """;
break;
case &#39;\&#39;&#39;:
result += "&#39;";
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($(&#39;message&#39;).value);
实际是调用了两次,Ajax类内部又调用一次。
服务端(Java版)需要做下转码:
String message = request.getParameter("message");
message = URLDecoder.decode(message, "UTF-8");
*/
注,客户端发送带有中文或HTML脚本的信息时,发送的信息必须调用:encodeURIComponent函数,例如:
String message = request.getParameter("message");
message = URLDecoder.decode(message, "UTF-8");
2、Demo.html
Ajax类<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="/static/imghwm/default1.png"  data-src="http://www.jb51.net/article/indicator_flower.gif"  class="lazy"    / alt="JavaScript Ajax class example code" ></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 >异步模式</button>
<button >非异步模式</button>
</body>
</html>


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Custom Google Search API Setup TutorialCustom Google Search API Setup TutorialMar 04, 2025 am 01:06 AM

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

Build Your Own AJAX Web ApplicationsBuild Your Own AJAX Web ApplicationsMar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

Example Colors JSON FileExample Colors JSON FileMar 03, 2025 am 12:35 AM

This article series was rewritten in mid 2017 with up-to-date information and fresh examples. In this JSON example, we will look at how we can store simple values in a file using JSON format. Using the key-value pair notation, we can store any kind

10 jQuery Syntax Highlighters10 jQuery Syntax HighlightersMar 02, 2025 am 12:32 AM

Enhance Your Code Presentation: 10 Syntax Highlighters for Developers Sharing code snippets on your website or blog is a common practice for developers. Choosing the right syntax highlighter can significantly improve readability and visual appeal. T

8 Stunning jQuery Page Layout Plugins8 Stunning jQuery Page Layout PluginsMar 06, 2025 am 12:48 AM

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

10  JavaScript & jQuery MVC Tutorials10 JavaScript & jQuery MVC TutorialsMar 02, 2025 am 01:16 AM

This article presents a curated selection of over 10 tutorials on JavaScript and jQuery Model-View-Controller (MVC) frameworks, perfect for boosting your web development skills in the new year. These tutorials cover a range of topics, from foundatio

What is 'this' in JavaScript?What is 'this' in JavaScript?Mar 04, 2025 am 01:15 AM

Core points This in JavaScript usually refers to an object that "owns" the method, but it depends on how the function is called. When there is no current object, this refers to the global object. In a web browser, it is represented by window. When calling a function, this maintains the global object; but when calling an object constructor or any of its methods, this refers to an instance of the object. You can change the context of this using methods such as call(), apply(), and bind(). These methods call the function using the given this value and parameters. JavaScript is an excellent programming language. A few years ago, this sentence was

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment