AJAX入门

mac2022-06-30  21

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script> <script type="text/javascript">   function button_click() { var text = $("#txtbox1"); var xmlhttp = new ActiveXObject("MicroSoft.XMLHTTP"); //创建xmlhttp对象 if (xmlhttp == null) { alert("xmlhttp对象创建失败!"); return false; } xmlhttp.open("POST", "Handler1.ashx?id=" + text.val() + "&ts=" + new Date(), false); //准备向服务器上的GetData1.ashx发送POST请求 //ts="+new Data()是为了每次都给服务器传不同的参数值,这样浏览器才不会直接从缓存中读取post一般不会缓存,get可能缓存。如果参数值是中文,要进行encodeURI("中国")

//XMLHTTP默认(推荐)不是同步请求,也就是open方法不像WebClientDonwloadString

那样把服务器返回的数据拿到才返回,是异步的,因此需要监听onreadystatechange事件

xmlhttp.onreadystatechange = function () { if (xmlhttp.readystate == 4) { //服务器完成响应 if (xmlhttp.status == 200) { //客户端接收成功 text.val(xmlhttp.responseText); } } } xmlhttp.send(); } </script> </head> <body> <input id="txtbox1" type="text" /><input type="button" οnclick="button_click()"/> </body> </html>

  

      xmlhttp.open("POST","GetData1.ashx?ts="+new Data(),false);  

 

 

 

       xmlhttp.onreadystatechange=function(){

                if(xmlhttp.readyState==4){        

                           if(xmlhttp.status==200){      //如果状态码为200表示成功返回数据

                            alert(xmlhttp.responseText);这里是服务器返回的文本

                           document.getElementById("textbox1").value=xmlhttp.responseText;//将文本返回到文本框中

                             

                            }

                            else {

                             alert("ajax服务器返回错误!");

                            }

                }

         }

          xmlhttp.send();//这时才开始发送请求

}

</script>

 

 

 

以下是jquery版ajax

<script type="text/javascript">

function button1_onclick(){

             var txtbox1=$("#txtbox1").val();

             var txtbox2=$("#txtbox2").val();

             $.post("getdata.ashx",{"id":txtbox1,"name":txtbox2},function(data,textStatus){

                        if(textStatus=="success"){

                         alert("成功");

                        }

                        else{

                        alert("ajax错误!");

                         }

             })

}

</script>

 

转载于:https://www.cnblogs.com/blackHorseplan/p/3899114.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)