创建一个 XMLHttpRequest对象
/**
* This function ,createXMLHttpRequest ,check to see what objects the
* browser supports in order to create the right kind of XMLHttpRequest
* type object to return.
*
* @return Returns an XMLHttpRequest type object or false.
* @type Object | Boolean
**/
function createXMLHttpRequest() {
var request = false;
if (window.XMLHttpRequest) {
if (typeof XMLHttpRequest != 'undefined') {
try {
request = new XMLHttpRequest;
} catch (e) {
request = false;
}
} else if (window.ActiveXObject) {
try {
request = new window.ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
try {
request = new window.ActiveXObject('Microsoft.XMLHTTP');
} catch (e) {
request = false;
}
}
}
}
return request;
}
//Example
var request = createXMLHttpRequest();
-----------------------------------------------------------
使用XMLHttpRequest发送数据,
/**
* This function,requestData ,takes the passed /request/ object and
* sends the passed /data/ to the passed /url/. The /request/
* object calls the /func/ function on /onreadystatechange/ .
*
* @param {Objcet} request The XMLHTTPRequest object to use.
* @param {String} url The URL to send the data request to.
* @param {String} method The method that the request should use to pass parameters.
* @param {String} data The data that is to be sent to the server through the request.
* @param {String} func The string name of the function to call on /onreadystatechange/ .
**/
function requestData(request, url, method, data, func) {
if (request) {
if (method == 'GET') {
request.open('GET', url + '?' + data, true);
} else {
request.open('POST', url, true);
}
request.onreadystatechange = func;
if (method == 'GET') {
request.send(null);
}
else {
request.send(data);
}
}
}
------------------------
接受相应文本
如果readyState不等于4(完成),就不需要处理,如果返回的状态不是200(成功),就需要返回fals表示错误。responseText属性里保存了服务器所发送内容的字符串版本。如果服务器返回XML,则系统自动将responseXML属性创建为可以像DOM那样分的DOM XML文档对象。
/**
* This function , parseResponse ,get the responseText
* from the /request/
*
* @param {Object} request The XMLHttpRequest which has been sent
* @return Return Return the responstText
**/
function parseResponse( request) {
if (request.readyState == 4) {
if (request.status == 200) {
return request.responseText;
} else {
return false;
}
}
}
字符串中的XML
有些时候想要动态拉出的XML来自一个XML文件或者XML字符串。在这种情况下,就需要把文件载入DOM文档对象中,以便分析XML。装载文件可以是用load方法,这个方法所有的浏览器都实现。不过要装载一个XML字符串却没有统一的方法。 Internet Exporer 有一个称为loadXML() 的方法,它是文档对象的一部分。遗憾的是,大多数其他浏览器灭有实现这一的方法。在这些情况下,开发人员将需要自己添加的跨浏览器兼容的loadXML()方法
为文档对象添加loadXML方法
/*Is this a DOM-compliant bowser*/
if(!window.ActiveXObject){
/**
*This method,loadXML,is a cross-browser method for DOM-compliant
*browsers that do not have this method natively. It loads an XML
*string into the DOM document for proper XML DOM parsing.
**/
document.property.loadXML=function(xml_string){
var doc=(new DOMParse()).parseFromString(xml_string,'text/xml');
/*Remove all initial children*/
while(this.hasChildNodes())
this.removChild(this.lastChild);
/*Insert and import nodes*/
for( i=0,il=doc.childNodes.length;i<il;)
this.appendChild(this.importNode(doc.childNodes[i++],true)) ;
};
}
将XML文件装载到DOM的跨浏览器代码:
/**
* This function, loadXMLFromFile takes the passed /file/ string file name
* and loads the contents into the DOM document.
*
* @param {String} file the string file name to load from
**/
function loadXMLFromFile(file){
/*Does this browser support ActiveX?(Internet Explorer)*/
if(window.ActiveXObject){
xmlDoc=new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async=false;
xmlDoc.load(file);
parseXML();
}else if(document.implementation && document.implementation.createDocument){
xmlDoc=document.implementation.createDocument('','',null);
xmlDoc.load(file);
xmlDoc.οnlοad=parseXML();
}
}
/*Example ,Cross-browser code to load an XML file into the DOM*/
var xmlDoc=null;
loadXMLFromFile('aaa.xml');
这个实例中,在调用parseXML() 函数分析全局的xmlDoc对象之前,我们以DOM文档对象的形式装载了 aaa.xml文件 。在调用 document.implementation.createDocument('','',null); 创建xmlDoc对象时,load方法的调用是一个同步调用,客户停止所有其他操作指导装载了xml文件。而ActiveX对象不会自动进行同步调用,Async属性需要设置成false才能获得与其对手相同的功能。
如果想让ActiveX对象异步动作,首先需要将async属性设置为true。然后,将onreadystatechange属性设置为调用函数。在每次readyState改变时被调用的函数必须检查文档装载的状态。 如下所示:
异步装载XML文件
/*Asynchronously loading an XML file*/
/**
* This function , loadXMLAsyncFromFile ,takes the passed /file/ string file name
* and loads the contents asynchronously into the DOM document.
*
* @param {String} ,file the string filename to load from.
* @see #verify
**/
function loadXMLAsyncFromFile(file){
xmlDoc=new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.anync=true;
xmlDoc.onreadychange=verify;
xmlDoc.load(file);
}
/**
* This function ,verify ,checks to see if the files if ready to be parsed
* before attempting to use it.
*
* @see #loadXMLAsyncFromFile
**/
function verify(){
/* Is the /readyState/ == 4? */
if(xmlDoc.readState == 4)
parseXML();
else
return false;
}
有时候我们需要从一个字符串创建DOM文档对象。比如从一个第三方应用程序获取动态数据,在这种场景中,我们无法控制代码,因为它不是开源的。这个应用程序也想客户发送XML数据,但却不以 text/xml 形式发送HTTP头中的Content-Type 。在这种情况下,responseXML属性会被设置为空(null),而且数据只会以字符串的形式存在于responseText属性里。这是loadXML方法就发挥作用了。
/* Loading an XML string into a DOM Document object .*/
/**
* This function ,parseResponse ,takes the XML response from the server
* and pulls out the elements it needs to dynamically alter the contents of a page.
**/
function parseResponse(){
if(request.readyState ==4){
if(request.status == 200){
var xmlString=request.responseText;
var response=null;
/* Does this browser support ActiveXObject (Internet Explorer)*/
if(window.ActiveXObjcet){
response=new ActiveXObject('Microsoft.XMLDOM');
response.async=false;
}else if(document.implementation && document.implementation.createDocument)
response=document.implementation.createDocument('','',null);
response.loadXML(xmlString);
var paramList=response.getElementsByTagName('param');
/* This will be the XML string to use*/
var out='<ul>';
/* Loop throuth the list taken from the XML response */
for(i=0,il<paramList.length;i<il;){
out+='<li>'+paramList[i++].firstChild.nodeValue+'</li>';
}
out+='</ul>';
document.getElementById('list').innerHTML=out;
}else
alert('There was a problem retrieving the data: \n'+request.statusText);
return=null;
}
}
Sarissa(http://sarissa.sourceforge.net)提供跨浏览器的解决方案,不仅仅是XPath还有XSLT。