`
三月的雪
  • 浏览: 17272 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

兼容IE,FireFox,Chrome和Safari的Ajax

阅读更多
    自己封装的ajax方法,兼容IE,FireFox,Chrome,Fafari等浏览器。方法内包括http请求发送和返回responose xml接收。
 
/*
    author: linyang
    date:  2012-01-30
*/
var myAjax = (function(){
    /*
        paramObj:{
            url: request url,
            method: GET or POST,
            encode: character
        }
        return xmlDOMParser
    */
    var _send_synchronous = function(paramObj){
            var url, method, encode,httpRequest,parser;
            url = paramObj.url;
            method = paramObj.method;
            encode = paramObj.encode;
            if(typeof method == 'undefined')
                    method = 'GET';
            if (window.ActiveXObject) {//IE
                    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } else {//FireFox,Chrome,Safari
                    httpRequest = new XMLHttpRequest();
                    }
            httpRequest.open(method, url, false);
            if(typeof encode != 'undefined')
                httpRequest.setRequestHeader("Content-Type", "text/html;charset="+encode);
            httpRequest.send();
            if (window.ActiveXObject) {//IE
                parser = new ActiveXObject("Microsoft.XMLDOM");
                parser.async = false;
                parser.load(httpRequest.responseXML);
            } else if (document.implementation.createDocument) {
                try {//FireFox
                    parser = document.implementation.createDocument("", "", null);
                    parser.async = false;
                    parser = (new DOMParser()).parseFromString(httpRequest.responseText, "text/xml");
                } catch(e) {//Chrome,Safari
                    var xmlhttp = new window.XMLHttpRequest();
                    xmlhttp.open("GET", httpRequest.responseText, false);
                    xmlhttp.send(null);
                    parser = xmlhttp.responseXML.documentElement;
                }
            }
            return parser;
        }
    /*
        paramObj:{
            url: request url,
            method: GET or POST,
            encode: character,
            param: post param,
            isAsync: boolean,
            parserHandler: function
        }
    */
    var _send_ajax = function(paramObj){
        var url,method,encode,httpRequest,param,isAsync,parser;
        var parserHandler;
            url = paramObj.url;
            method = paramObj.method.toUpperCase();
            encode = paramObj.encode;
            if(method=='GET')
                    param = null;
                else if(method=='POST')
                    param = paramObj.param;
            isAsync = paramObj.isAsync;
            parserHandler = paramObj.parserHandler;
        if (window.ActiveXObject) {//IE
                httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } else {//FireFox,Chrome,Safari
                    httpRequest = new XMLHttpRequest();
                }
        httpRequest.onreadystatechange = function(){
                if(httpRequest.readyState==4){
                    if(httpRequest.status==200){
                        if (window.ActiveXObject) {//IE
                                parser = new ActiveXObject("Microsoft.XMLDOM");
                                parser.async = false;
                                parser.load(httpRequest.responseXML);
                            } else if (document.implementation.createDocument) {
                                try {//FireFox
                                    parser = document.implementation.createDocument("", "", null);
                                    parser.async = false;
                                    parser = (new DOMParser()).parseFromString(httpRequest.responseText, "text/xml");
                                } catch(e) {//Chrome,Safari
                                    var xmlhttp = new window.XMLHttpRequest();
                                    xmlhttp.open("GET", httpRequest.responseText, false);
                                    xmlhttp.send(null);
                                    parser = xmlhttp.responseXML.documentElement;
                                }
                            }
                            parserHandler.apply(parser,[]);
                    }else{
                        alert("远程服务调用失败!");
                    }
                }
            }        
        httpRequest.open(method, url, isAsync);
        if(typeof encode != 'undefined')
            if(method=='GET')
                    httpRequest.setRequestHeader("Content-Type", "text/html;charset="+encode);
                else if(method=='POST')
                    httpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset="+encode);
        httpRequest.send(param);
    }
    return {
        sendSynchronize:_send_synchronous,
        sendAjax:_send_ajax
    }
})();
  

使用例子:(来源于某网上商店 ^ ^)
myAjax.sendAjax({
					url:"PointTransAction.do",
					method:'POST',
					encode:'GBK',
					param:"giftid=" + id + "&time=" + new Date(),
					isAsync:true,
					parserHandler:function(){
						var flag = this.getElementsByTagName('ret')[0].getAttribute('flag');
						var msg = this.getElementsByTagName('ret')[0].getAttribute('msg');
						if (flag == '0')
							//do something
			  			    else
							alert(msg);
					}
				});

说明:1,myAjax这个小的JavaScript库对外提供了两个方法:sendSynchronize和sendAjax,但其实sendAjax才是称得上真正的ajax,因为sendSynchronize方法只支持同步,sendAjax可以通过isAsync设置是否使用异步调用。之所以写了sendSynchronize是为了纪念以前在宇宙行那段磕磕绊绊的日子吧。。。
      2,parserHandler为传入的回调函数,其中的this关键字是parser的引用。
      3,库中的两个方法对xml解析的时候使用的都是同步加载,如果要实现异步加载那么同样需要回调函数:IE下onreadystatechange事件,而FireFox下是onload事件。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics