简单的Ajax例子
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>ajaxѧϰ</title> <meta http-equiv="content-type" content="text/html;charset=UTF-8"/> <script type="text/javascript"> var xmlHttp; function createXMLHttpRequest(){ if(window.XMLHttpRequest){ //for IE7+,Firefox,Chrome,Opera,Safari xmlHttp = new XMLHttpRequest(); }else{ //for IE6,IE5 xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } } function start0Request(){ createXMLHttpRequest(); //open(method,url,async) //规定请求的类型、URL 以及是否异步处理请求。 //method:请求的类型;GET 或 POST url:文件在服务器上的位置 async:true(异步)或 false(同步) xmlHttp.open("get","http://m.weather.com.cn/data/101100101.html",false); xmlHttp.send(); var result = xmlHttp.responseText; alert(result); document.getElementById("weatherID").innerHTML = ""; document.getElementById("weatherID").innerHTML = result ; } function start1Request(){ createXMLHttpRequest(); xmlHttp.open("get","http://m.weather.com.cn/data/101100101.html",true); document.getElementById("weatherID").innerHTML = ""; //onreadystatechange 存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。 //readyState 存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。 //0: 请求未初始化 1: 服务器连接已建立 2: 请求已接收 3: 请求处理中 4: 请求已完成,且响应已就绪 //status 200: "OK" 404: 未找到页面 xmlHttp.onreadystatechange = function(){ if(4 == xmlHttp.readyState && 200 == xmlHttp.status){ var result = xmlHttp.responseText; document.getElementById("weatherID").innerHTML = result ; } } xmlHttp.send(); } </script> </head> <body> <input type="button" value="ajax同步" onclick="start0Request()"/> <input type="button" value="ajax异步" onclick="start1Request()"/> <div id="weatherID"></div> </body> </html>
简单的使用Ajax,多多指教!谢谢!