Ajax核心代码

来源:互联网 发布:贵州大数据产业规划 编辑:程序博客网 时间:2024/05/22 13:49

 

 

<script type="text/javascript">
   
       function btnClick(){
          var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");//创建XMLHTTP对象,相当于WebClient
         
          if(!xmlhttp){
              alert("创建xmlhttp对象异常!");
              return false;
         
          }
          xmlhttp.open("POST","GetDate1.ashx?id=33&ts="+new Date(),false);//准备向服务器的GetDate1.ashx发出Post请求,XMLHTTP默认(也推荐)不是同步请求的,也就是open方法并不像WebClient的DownloadString那样把服务器返回的数据拿到才返回,是异步的,无法直接拿到send的返回值,因此需要监听onreadystatechange事件
         
          xmlhttp.onreadystatechange = function(){
              if (xmlhttp.readyState ==4){ //服务器完成(可能成功也可能失败)
                  if(xmlhttp.status==200){ //如果状态为200则是成功
                  //alert(xmlhttp.responseText);
                  document.getElementById("Text1").value = xmlhttp.responseText; //responseText属性为服务器返回的文本
                 
                  }
                  else{
                      alert("AJAX服务器返回错误!");
                  }
              }
          xmlhttp.send();//这时才开始返回请求
          }

    </script>