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的實例代碼,希望對大家有所幫助,在使用過程發現有任何疑問歡迎給我留言,小編會及時回復大家的。在此小編非常感謝大家對網站的支持,相信我們會做的更好!