- /**
- * ajax封装以及xml封装
- * User: Rex
- * To change this template use File | Settings | File Templates.
- */
- (function(window){
- function _Ajax(url){
- this.url=url;
- this.browser=(function(){
- if(navigator.userAgent.indexOf("MSIE")>0) {
- return "MSIE";//IE浏览器
- }else{
- return "other";//其他
- }})();
- };
- _Ajax.prototype={
- get:function(parms){
- var result;
- var xmlhttp;
- if(this.browser=='MSIE'){
- try{
- xmlhttp=new ActiveXObject('microsoft.xmlhttp');
- }catch(e){
- xmlhttp=new ActiveXObject('msxml2.xmlhttp');
- }
- }else{
- xmlhttp=new XMLHttpRequest();
- };
- xmlhttp.onreadystatechange=function(){
- result = xmlhttp.responseText;//闭包,不能采用this.属性
- };
- xmlhttp.open('GET',this.url+'?'+parms,false);//true无法抓取数据,why?
- xmlhttp.send(null);
- return result;
- },
- post:function(parms){
- var result;
- var xmlhttp;
- if(this.browser=='MSIE'){
- xmlhttp=new ActiveXObject('microsoft.xmlhttp');
- }else{
- xmlhttp=new XMLHttpRequest();
- };
- xmlhttp.onreadystatechange=function(){
- result = xmlhttp.responseText;//闭包,不能采用this.属性
- };
- xmlhttp.open('POST',this.url,false);//需设为false,否则无法抓取responseText
- xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//POST中,这句必须
- xmlhttp.send(parms);
- return result;
- }
- };
- /**
- * ajax加载文件
- * @param url 地址
- * @returns {_Ajax}
- */
- window.ajax=function(url){
- return new _Ajax(arguments[0]);
- };
- /**
- * 解析xml字符串
- * @param xmlString
- * @returns {null}
- */
- window.loadXML = function(xmlString){
- var xmlDoc=null;
- //判断浏览器的类型
- //支持IE浏览器
- if(!window.DOMParser && window.ActiveXObject){ //window.DOMParser 判断是否是非ie浏览器
- var xmlDomVersions = ['MSXML.2.DOMDocument.6.0','MSXML.2.DOMDocument.3.0','Microsoft.XMLDOM'];
- for(var i=0;i<xmlDomVersions.length;i++){
- try{
- xmlDoc = new ActiveXObject(xmlDomVersions[i]);
- xmlDoc.async = false;
- xmlDoc.loadXML(xmlString); //loadXML方法载入xml字符串
- break;
- }catch(e){
- }
- }
- }
- //支持Mozilla浏览器
- else if(window.DOMParser && document.implementation && document.implementation.createDocument){
- try{
- /* DOMParser 对象解析 XML 文本并返回一个 XML Document 对象。
- * 要使用 DOMParser,使用不带参数的构造函数来实例化它,然后调用其 parseFromString() 方法
- * parseFromString(text, contentType) 参数text:要解析的 XML 标记 参数contentType文本的内容类型
- * 可能是 "text/xml" 、"application/xml" 或 "application/xhtml+xml" 中的一个。注意,不支持 "text/html"。
- */
- domParser = new DOMParser();
- xmlDoc = domParser.parseFromString(xmlString, 'text/xml');
- }catch(e){
- }
- }
- else{
- return null;
- }
- return xmlDoc;
- }
- })(window);
- //该片段来自于http://www.codesnippet.cn/detail/151120137203.html
来源: http://www.codesnippet.cn/detail/151120137203.html