使用 JavaScript 和 Ajax 发出异步请求

一、 以支持多种浏览器的方式创建 XMLHttpRequest 对象

    var xmlHttp = false;
    if(window.ActiveXObject){ 
        try {
              xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
            
          } catch (othermicrosoft) {
                try {
                 xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (failed) {
                  xmlHttp = false;
                }
          }   
    }
    else if (window.XMLHttpRequest)   { 
        try{ 
            xmlHttp= new  XMLHttpRequest();
        } catch(fail){
            xmlHttp= false ;     
        } 
      }
    if (!xmlHttp)
      alert("Error initializing XMLHttpRequest!");
 

二、通过GET方法向服务器发出 Ajax 请求

    var name = document.getElementById("name").value;
    var password = document.getElementById("password").value;

    if ((name == null) || (name == "")) {
        return;
    }
    if ((password == null) || (password == "")) {
        return;
    }
  // Build the URL to connect to
    var url = "/ajax/AjaxServlet?name=" + escape(name) + "&password=" + escape(password);
  // Open a connection to the server
    xmlHttp.open("HEAD", url, true);
  // Setup a function for the server to run when it's done
    xmlHttp.onreadystatechange = updatePage;
  // Send the request
    xmlHttp.send(null);
}
 

xmlHttp (要记住,这是 XMLHttpRequest 对象实例)的 onreadystatechange 属性可以告诉服务器在运行完成 后(可能要用五分钟或者五个小时)做什么。因为代码没有等待服务器,必须让服务器知道怎么做以便您能作出响应。在这个示例中,如果服务器处理完了请求,一个特殊的名为 updatePage() 的方法将被触发。


function updatePage() {
     if (xmlHttp.readyState == 4) {
       if (xmlHttp.status == 200) {
//         alert("updatePage() called with ready state of " + xmlHttp.readyState);
         alert(xmlHttp.getAllResponseHeaders());
         
       } else if (xmlHttp.status == 404) {
         alert ("Requested URL is not found.");
       } else if (xmlHttp.status == 403) {
         alert("Access denied.");
       } else
         alert("status is " + xmlHttp.status);
     }

//  if (xmlHttp.readyState == 4) {
//    var response = xmlHttp.responseText;
//    document.getElementById("test").value = response;
//    alert("updatePage() called with ready state of " + xmlHttp.readyState);
// }
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值