<!DOCTYPE html> <html> <head> <title>ajax</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script language="javascript" type="text/javascript"> //通过这个函数来异步获取信息 function Ajax() { var xmlHttpReq = null; //声明一个空对象用来装入XMLHttpRequest if(window.ActiveXObject) { //IE5 IE6是以ActiveXObject的方式引入XMLHttpRequest xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP"); } else if(window.XMLHttpRequest) { xmlHttpReq = new XMLHttpRequest(); } if(xmlHttpReq != null) { //如果对象实例化成功 xmlHttpReq.open("GET", "example.txt", true); //调用open()方法并采用异步方式 xmlHttpReq.onreadystatechange = RequestCallBack; //设置回调函数 xmlHttpReq.send(null); } function RequestCallBack() { if(xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200) { document.getElementById("resText").innerHTML = xmlHttpReq.responseText; } } } </script> </head> <body> 1.创建xhr对象,并实例化 2.设置回调函数(判断readyState和status的值;写入值)在open之前 3.调用open()方法 4.调用send()方法 <h3>查看留言:</h3> <input type="button" value="Ajax提交" onclick="Ajax();" /> <div id="resText"></div> </body> </html>
原文:http://www.cnblogs.com/zyxie154/p/7440592.html