//创建XMLHttpRequest对象
function getXMLHttpRequest() { HTTP_Request = false; if(window.XMLHttpRequest) { HTTP_Request = new XMLHttpRequest(); if(HTTP_Request.overrideMimeType) HTTP_Request.overrideMimeType("text/xml"); } else { if(window.ActiveXObject) { try { HTTP_Request = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { try { HTTP_Request = new ActiveXObject("Microsoft.XMLHTTP"); }catch(e) { } } } } return HTTP_Request; } //发送请求 /* @HTTP_Request 异步请求对象 @url 请求位置 @method 请求方法 @content 请求内容 eg. param1=xxx1¶m2=xxx2 @callBack 请求回调 */ function send_request(HTTP_Request,url,method,content,callBack) { if(!HTTP_Request) { alert('无法创建异步请求对象!'); return; } HTTP_Request.onreadystatechange = callBack; if(method.toupperCase() == 'GET') { HTTP_Request.open(method,true); HTTP_Request.setRequestHeader('Content-Type','text/html;charset=UTF-8'); } else if(method.toupperCase == 'POST') { HTTP_Request.open(method,'application/x-www-form-urlencoded'); } else { alert('请求方法出错!'); return; } HTTP_Request.send(content); } //返回文本的 function getWebContent() { var webConReq = getXMLHttpRequest();//ajax不支持跨跨域访问 send_request(webConReq,'./servlet/testServlet','get',null,function() { if(webConReq.readyState == 4) { if(webConReq.status == 200) { var doc = webConReq.responseText; if(doc) { document.getElementById("pageCon").innerHTML = doc; } } else { alert('请求失败!'); } } } ); } //返回xml function getXml() { var webConReq = getXMLHttpRequest();//ajax不支持跨跨域访问 send_request(webConReq,'./NewFile.xml',function() { if(webConReq.readyState == 4) { if(webConReq.status == 200) { var doc = webConReq.responseXML; if(doc) { var root = doc.getElementsByTagName("items")[0]; var items = root.getElementsByTagName("item"); var html = ''; for(var i=0;i<items.length;i++) { html += "id:" + items[i].getAttribute('id'); html += " name:" + items[i].getAttribute('name'); } document.getElementById("xml").innerHTML = html; } } else { alert('请求失败!'); } } } ); } <a href="javascript:getWebContent();">异步获取页面</a> <font id="pageCon"></font><br> <a href="javascript:getXml();">异步XML</a> <font id="xml"></font>