AJAX:Asynchronous Javascript and xml 異步,Js和Xml 交互式網頁開發 不刷新頁面,與服務器交互 詳情請參照Jquery工具指南
用在瀏覽器端的技術,無刷新,經過XmlHttpRequest訪問頁面
純js版----------javascript
if(XmlHttpRequest){ //判斷是否支持XmlHttpRequest xhr= new XmlHttpRequest(); // 建立XmlHttpRequest對象 } else{ xhr= new Activexobject("Microsoft.XMLHTTP"); //不支持XmlHttpRequest,使用此方法建立 } xhr.open("get|post","url",true); xhr.send(); // 開始發送 xhr.onreadystatechange= function(){ // 回調函數,當服務器將數據返回給瀏覽器觸發方法 if(xhr.readyState==4) //0沒調用open方法,1表示未調用send方法,2正在等待狀態碼和頭的返回,3 已接受部分數據,但還沒接受完,不能使用該對象的屬性和方法,4已加載,全部數據執行完畢 if(xhr.status==200){ // 響應狀態碼,表示頁面執行無誤 alert(xhr.responseText); // 輸出接受到的文本 } }
在send中寫數據。並添加請求報頭
如java
xhr.setRequestHeader("Content-Type",application/x-www-form-urlencoded) xhr.send("id=123&pwd=456");
-------------------------------------
Jquery版
強大的Jquery。。只須要get頁面就夠了ajax
$.get("url",{"id" : "123","pwd":456},function(data)){ //自動把參數當作get請求傳輸 alert(data) }
只須要post頁面。瀏覽器
$.post("url",{"id" : 123,"pwd":456},function(data)){ //post請求 alert(data) }
//第三種寫法服務器
$.ajax({ type="get"| post, url="...", data:"參數", success:function(msg){...} // msg爲從服務器接受到的數據 })