认识Ajax:
- 传统的web采用同步交互的形式,即用户向服务器发送一个请求,服务器根据请求执行任务并返回结果
- Ajax采用异步交互
Ajax组成部分:
- javascript
- css
- DOM
- XMLHttpRequest
异步对象连接服务器
- 创建:
var xmlHttp; functin createXMLHttpRequest(){ if(window.ActiveXObject) xmlHttp=new ActiveXObject("Micsoft.XMLHTTP"); else if(window.XMLHttpRequest) xmlHttp=new XMLHttpRequest(); }
- 建立请求:
xmlHttp.open("GET","xx.aspx",true);false :同步交互
onreadystatechange事件
xmlHttp.onreadystatechange=function(){ if(xmlHttp.readyState==4&&xmlHttp.status==200) { //dosometing } )
- send发送:
xmlHttp.send(null);
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>XMLHttpRequest</title> <script language="javascript"> var xmlHttp; function createXMLHttpRequest(){ if(window.ActiveXObject) xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); else if(window.XMLHttpRequest) xmlHttp = new XMLHttpRequest(); } function startRequest(){ createXMLHttpRequest(); xmlHttp.open("GET","9-1.aspx",true); xmlHttp.onreadystatechange = function(){ if(xmlHttp.readyState == 4 && xmlHttp.status == 200) alert("服务器返回: " + xmlHttp.responseText); } xmlHttp.send(null); } </script> </head> <body> <input type="button" value="测试异步通讯" onClick="startRequest()"> </body> </html>
GET VS POST
GET: var queryString="firstName=aa&birthday=0624"; var url="xx.aspx?"+queryString+"×tamp="+new Date().getTime(); xmlHttp.open("GET“,url); xmlHttp.send(null);//该语句只发送null
POST
POST: var queryString="firstName=aa&birthday=0624"; var url="xx.aspx?timestamp="+new Date().getTime(); xmlHttp.open("POST“,url); xmlHttp.setRequestHeader("Content-Type","app;ication/x-www-form-urlencoded"); xmlHttp.send(queryString);//该语句负责发送数据