標籤:表示 ext form 學習 pre 頁面 ntb mod 多次
ajax全稱是:asynchronous javasctipt and xml。
1.為什麼須要ajax?
一般web程式與server的互動是:頁面發送請求等待server處理,server處理資料。使用者頁面重新整理整個頁面。從而完畢了一次互動。
假設用這樣的同步方式進行多次這樣的頁面與server的互動。使用者將會須要非常多時間去等待server處理。
ajax非同步處理的思想是:當頁面發送請求後。交給server處理,server處理的同一時候,頁面無須等待能夠進行其它的操作,當server處理完畢後。在當前頁面顯示結果。無須重新整理整個頁面。
2.ajax的簡單實現
實現ajax須要用到javascript的XMLHttpRequest對象。
實現過程
1)建立對象(不同瀏覽器有不同的建立方法,一般須要考慮ie和非ie瀏覽器)
ie瀏覽器要用到ActiveXObject。
非ie瀏覽器可直接建立XMLHttpRequest對象執行個體。
2)發送請求。
發送請求前須要先建立一個與server的串連。它須要的參數有發送類型、串連的url、非同步串連狀態值等。
> 發送類型:GET/POST等。
> url:串連地址 + ? + 傳送的值 (+ & + 傳送的值..) [這裡是用的get方式]
> 非同步串連狀態值:true / false。默覺得true。true表示非同步串連。
在發送請求前還要建立一個返回函數,它是用來指定server響應後要啟動並執行內容。
發送請求。
3)server響應函數
3.一個簡單一實例
<!DOCTYPE html><html><head><meta charset="utf-8" /><title></title><script>//var xmlHttp = new XMLHttpRequest();/*建立XMLHttpRequest對象*/var xmlHttp = false;/*@cc_on @*/ //ie條件編譯/*@if (@_javascript_version >= 5)try{xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");}catch(e){xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");}catch(e2){xmlHttp = false;}@end @*/if(!xmlHttp && typeof XMLHttpRequest != ‘undefined‘){xmlHttp = new XMLHttpRequest();}function callServer(){//擷取name和password值var name = document.getElementById("name").value;var password = document.getElementById("password").value;//推斷name和password是否為空白if((name == "null") || (name == "")) return ;if(password == "null" || password == "") return ;//建立要串連的urlvar url = "check.php?name=" + escape(name) + "&password" + escape(password);//建立一個server的請求xmlHttp.open("GET", url, true);//建立server完畢後執行的函數xmlHttp.onreadystatechange = updatePage;//發送請求xmlHttp.send(null);}function updatePage(){if(xmlHttp.readyState == 4){ //http就緒狀態if(xmlHttp.status == 200){ //推斷http狀態碼var response = xmlHttp.responseText; //處理server響應document.getElementById("ajax-result").value = response;}else if(xmlHttp.status == 404){alert("Request url does not exist!");}else{alert("ERROR:status code is" + xmlHttp.status);}}}</script></head><body><div id="form"><form method="get">name:<input type="text" id="name" onchange="callServer()"/><br>passwiord:<input type="text" id="password" onchange="callServer()"><br>result:<input type="text" id="ajax-result"/></form></div></body></html>
[ajax 學習筆記] ajax初試