您的位置:首页 > 理论基础 > 计算机网络

Ajax XMLHttpRequest 用法

2007-12-06 14:19 211 查看
原地址:http://www.yuleweb.com/Article/ajax/AJAX4/200704/4868.html

<html xmlns="http://www.w3.org/1999/xhtml" >


<head>


<title>xmlhttprequest ajax demo</title>




<script type ="text/javascript" language ="javascript" >



var req; //定义变量,用来创建xmlhttprequest对象


function creatReq() // 创建xmlhttprequest,ajax开始






{


var url="ajaxServer.aspx"; //要请求的服务端地址


if(window.XMLHttpRequest) //非IE浏览器,用xmlhttprequest对象创建






{


req=new XMLHttpRequest();


}


else if(window.ActiveXObject) //IE浏览器用activexobject对象创建






{


req=new ActiveXObject("Microsoft.XMLHttp");


}




if(req) //成功创建xmlhttprequest






{


req.open("GET",url,true); //与服务端建立连接(请求方式post或get,地址,true表示异步)


req.onreadystatechange = callback; //指定回调函数


req.send(null); //发送请求


}


}




function callback() //回调函数,对服务端的响应处理,监视response状态






{


if(req.readystate==4) //请求状态为4表示成功






{


if(req.status==200) //http状态200表示OK






{


Dispaly(); //所有状态成功,执行此函数,显示数据


}


else //http返回状态失败






{


alert("服务端返回状态" + req.statusText);


}


}


else //请求状态还没有成功,页面等待







{


document .getElementById ("myTime").innerHTML ="数据加载中

";


}


}




function Dispaly() //接受服务端返回的数据,对其进行显示






{


document .getElementById ("myTime").innerHTML =req.responseText;


}




</script>


</head>


<body>


<div id="myTime"></div>




<input id="Button1" type="button" value="Get Time" onclick ="creatReq();"/>


</body>


</html>服务端ajaxServer.aspx代码


public partial class ajaxServer : System.Web.UI.Page






{


protected void Page_Load(object sender, EventArgs e)






{


System.Threading.Thread.Sleep(1000); //为了看到ajax效果,将当前线程延时1000毫秒


Response.Write(DateTime .Now .ToString ()); //输出当前时间


}


}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: