AJAX = Asynchronous JavaScript and XML.
AJAX 是一種創(chuàng)建快速動(dòng)態(tài)網(wǎng)頁(yè)的技術(shù)。
AJAX 通過(guò)在后臺(tái)與服務(wù)器交換少量數(shù)據(jù)的方式,允許網(wǎng)頁(yè)進(jìn)行異步更新。這意味著有可能在不重載整個(gè)頁(yè)面的情況下,對(duì)網(wǎng)頁(yè)的一部分進(jìn)行更新。
實(shí)現(xiàn)ajax之前必須要?jiǎng)?chuàng)建一個(gè) XMLHttpRequest 對(duì)象。如果不支持創(chuàng)建該對(duì)象的瀏覽器,則需要?jiǎng)?chuàng)建 ActiveXObject.具體方法如下:
var xmlHttp; function createxmlHttpRequest(){ if (window.ActiveXObject) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } else if (window.XMLHttpRequest){ xmlHttp=new XMLHttpRequest(); } }
(1)下面使用上面創(chuàng)建的xmlHttp實(shí)現(xiàn)最簡(jiǎn)單的ajax get請(qǐng)求:
function doGet(url){ // 注意在傳參數(shù)值的時(shí)候最好使用encodeURI處理一下,以防出現(xiàn)亂碼 createxmlHttpRequest(); xmlHttp.open("GET",url); xmlHttp.send(null); xmlHttp.onreadystatechange = function(){ if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200)) { alert('success'); } else { alert('fail'); } } }
(2)使用上面創(chuàng)建的xmlHttp實(shí)現(xiàn)最簡(jiǎn)單的ajax post請(qǐng)求:
function doPost(url,data){ // 注意在傳參數(shù)值的時(shí)候最好使用encodeURI處理一下,以防出現(xiàn)亂碼 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'); } } }
以上內(nèi)容是小編給大家介紹的JavaScript實(shí)現(xiàn)ajax的實(shí)例代碼,希望對(duì)大家有所幫助,在使用過(guò)程發(fā)現(xiàn)有任何疑問(wèn)歡迎給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此小編非常感謝大家對(duì)VeVb武林網(wǎng)網(wǎng)站的支持,相信我們會(huì)做的更好!