通过实例来理解ajax

时间:2023-01-02 02:38:15

点击一个按钮,然后将信息显示到指定的div内。

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>FirstTest.html</title>
<script language="javascript">
function onclickAjax(){
var xmlHttp;
//分浏览器创建XMLHttp对象
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}else if(window.ActiveXObject){
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP")
}
//设置请求类型
xmlHttp.open("POST","test.do?method=ajaxTest&&msg="+new Date(),true);
//回调函数
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
document.getElementById("testid").value=xmlHttp.responseText;
}else{
alert("AJAX服务器返回错误!");
}
}
}
//发送请求
xmlHttp.send();
}
</script>
</head> <body>
<input type="button" value="测试" onclick="onclickAjax()">
<div id="testid">
</div>
</body>
</html>

具体参考http://www.cnblogs.com/lsnproj/archive/2012/02/07/2340395.html

http://www.cnblogs.com/lsnproj/archive/2012/02/09/2341524.html

http://www.cnblogs.com/aylin/p/5732242.html(包含跨域)