微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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,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> 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐