AJAX = Asynchronous JavaScript and XML.
AJAX 是一種建立快速動態網頁的技術。
AJAX 通過在後台與伺服器交換少量資料的方式,允許網頁進行非同步更新。這意味著有可能在不重載整個頁面的情況下,對網頁的一部分進行更新。
實現ajax之前必須要建立一個 XMLHttpRequest 對象。如果不支援建立該對象的瀏覽器,則需要建立 ActiveXObject.具體方法如下:
var xmlHttp; function createxmlHttpRequest(){ if (window.ActiveXObject) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } else if (window.XMLHttpRequest){ xmlHttp=new XMLHttpRequest(); } }
(1)下面使用上面建立的xmlHttp實現最簡單的ajax get請求:
function doGet(url){ // 注意在傳參數值的時候最好使用encodeURI處理一下,以防出現亂碼 createxmlHttpRequest(); xmlHttp.open("GET",url); xmlHttp.send(null); xmlHttp.onreadystatechange = function(){ if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200)) { alert('success'); } else { alert('fail'); } } }
(2)使用上面建立的xmlHttp實現最簡單的ajax post請求:
function doPost(url,data){ // 注意在傳參數值的時候最好使用encodeURI處理一下,以防出現亂碼 createxmlHttpRequest(); xmlHttp.open("POST",url); xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xmlHttp.send(data); xmlHttp.onreadystatechange = function() { if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200)) { alert('success'); }else{ alert('fail'); } } }
以上內容是小編給大家介紹的JavaScript實現ajax的執行個體代碼,希望對大家有所協助,在使用過程發現有任何疑問歡迎給我留言,小編會及時回複大家的。在此小編非常感謝大家對雲棲社區網站的支援,相信我們會做的更好!