Posted on 2008-04-19 15:11
semovy 阅读(434)
评论(0) 编辑 收藏 所属分类:
ajax
//创建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,url,true);
http_request.setRequestHeader('Content-Type','text/html;charset=UTF-8');
}
else if(method.toUpperCase == 'POST')
{
http_request.open(method,url,true);
http_request.setRequestHeader('Content-Type','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','get',null,
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>