1.在學(xué)習ajax之前應(yīng)該基本的了解以下內(nèi)容:
HTML / XHTML
CSS
JavaScript / DOM
2.什么是AJAX?
AJAX =異步JavaScript和XML。
3.ajax的基礎(chǔ)是XMLHttpRequest對象。所有現(xiàn)代瀏覽器支持XMLHttpRequest對象(IE5和IE6使用ActiveXObject對象)。
所有現(xiàn)代瀏覽器(IE7 +,火狐,Chrome,蘋果Safari和Opera)有一個內(nèi)置的XMLHttpRequest對象。
創(chuàng)建一個XMLHttpRequest對象的語法:
variable =new XMLHttpRequest();
Internet Explorer (IE5 and IE6) 使用 ActiveX 對象:
variable =new ActiveXObject("Microsoft.XMLHTTP");
創(chuàng)建一個滿足所有瀏覽器的對象:
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
4.發(fā)送一個請求到服務(wù)器
向服務(wù)端發(fā)送一個請求,XMLHttpRequest對象的open()和send()方法:
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
MethodDescription
open( method,url,async )
指定request的類型,url,是否請求異步
method : the type of request: GET or POST
url : the location of the file on the server
async : true (asynchronous) or false (synchronous)異步
send( string )把請求發(fā)送到服務(wù)端
string : Only used for POST requests
5. get請求:
簡單 GET 請求:
xmlhttp.open("GET","demo_get.asp",true);
xmlhttp.send();
通過上面的例子,可以得到緩存的結(jié)果
為區(qū)分緩存結(jié)果,可以給url添加一個唯一id
xmlhttp.open("GET","demo_get.asp?t=" + Math.random(),true);
xmlhttp.send();
如果發(fā)送請求時,添加一些參數(shù),可以把參數(shù)加到url上
xmlhttp.open("GET","demo_get2.asp?fname=Henry&lname=Ford",true);
xmlhttp.send();
6. post 請求:
簡單的post請求
xmlhttp.open("POST","demo_post.asp",true);
xmlhttp.send();
發(fā)送html表單數(shù)據(jù),添加http請求頭(使用setRequestHeader(). ),指定要發(fā)送的數(shù)據(jù)在send()方法上:
xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");
MethodDescription
setRequestHeader( header,value )Adds HTTP headers to the request.
header : specifies the header name
value : specifies the header value
7.Asynchronous 異步
如果要使用異步,open方法的參數(shù)async 必須是true
xmlhttp.open("GET","ajax_test.asp",true);
發(fā)送異常請求是一個巨大的提高,許多請求在服務(wù)端非常耗時,導(dǎo)致客戶端長時間等待。在使用ajax后,客戶端不需要等待服務(wù)端,反而可以執(zhí)行其它腳本,并且response準備好同時處理響應(yīng)
當async=true時,響應(yīng)準備就緒時,指定一個函數(shù)獲取響應(yīng)結(jié)果與執(zhí)行操作
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
當Async=false時,即xmlhttp.open("GET","ajax_info.txt",false);
使用async=false是不推薦的,但是有很少部分的請求是可以使用的.
javaScript在Server端沒有響應(yīng)就緒時,不可以繼續(xù)執(zhí)行。如果server很忙很慢,客戶端只能掛起等待。
注意: 使用async=false, 不可以寫onreadystatechange方法,只需要在send()方法后寫響應(yīng)內(nèi)容
xmlhttp.open("GET","ajax_info.txt",false);
xmlhttp.send();
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;