Professional Documents
Culture Documents
AJAX khng phi l mt ngn ng lp trnh mi m l mt cch thc mi s dng nhng chun c. Vi AJAX bn c th to ra nhng ng dng web tt, nhanh v thn thin vi ngi dng hn. AJAX da trn nhng yu cu JavaScript v HTML. Bt u hc ngay AJAX!
www.w3schools.com
Cc chun v web c s dng trong AJAX c nh ngha rt tt, v c tt c trnh duyt ph bin h tr. Cc ng dng AJAX u c lp vi trnh duyt v nn.
www.w3schools.com
www.w3schools.com
i tng XMLHttpRequest
Bng cch s dng i tng XMLHttpRequest, nh pht trin web c th cp nht trang vi d liu t my ch sau khi trang c np. AJAX c Google lm cho tr nn ph bin vo nm 2005 (vi Google Suggest). Google Suggest s dng i tng XMLHttpRequest to ra mt giao din rt linh hot: Khi bn bt u g ch trong hp tm kim ca Google, mt JavaScript gi nhng ch n my ch v my ch tr v mt danh sch ca nhng gi . i tng XMLHttpRequest c h tr trong Internet Explorer 5.0+, Safari 1.2, Mozilla 1.0 / Firefox, Opera 8+, v Netscape 7.
www.w3schools.com
Mt v d AJAX
ng dng AJAX u tin ca bn
hiu AJAX lm vic th no, chng ta s to mt ng dng AJAX nh. Trc tin, chng ta s to mt biu mu HTML chun vi hai trng vn bn: username v time. Trng username s c in bi ngi dng v trng time s c in bng cch s dng AJAX. Tp tin HTML s c t tn l "testAjax.htm", v n nh th ny (ch rng biu mu HTML bn di khng c nt gi d liu!):
<html> <body> <form name="myForm"> Name: <input type="text" name="username" /> Time: <input type="text" name="time" /> </form> </body> </html>
www.w3schools.com
www.w3schools.com
} } } } </script> <form name="myForm"> Name: <input type="text" name="username" /> Time: <input type="text" name="time" /> </form> </body> </html>
Gii thch v d: Trc tin to bin xmlHttp gi i tng XMLHttpRequest. Sau th to i tng vi XMLHttp = new XMLHttpRequest(). y l cho Firefox, Opera, v Safari browsers. Nu n b li, th xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") dnh cho Internet Explorer 6.0+, nu n vn b li. Th tip xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") dnh cho Internet Explorer 5.5+. Nu c ba cch trn u khng lm vic, ngha ngi dng ang c mt trnh duyt qu c, v h s nhn c mt thng bo v vic trnh duyt ca h khng h tr AJAX. Ch : on m tng thch trnh duyt trn di v kh phc tp. Tuy nhin, y l on m bn c th s dng mi khi cn to mt i tng XMLHttpRequest, khi y bn ch cn chp v dn vo bt k ni no bn cn n. on m trn tng thch vi tt c trnh duyt ph bin hin nay nh Internet Explorer, Opera, Firefox, v Safari. Phn k tip cho bn thy cch s dng i tng the XMLHttpRequest giao tip vi my ch.
www.w3schools.com
Thuc tnh readyState Thuc tnh readyState lu gi trng thi phn hi ca my ch. Mi ln readyState thay i, hm onreadystatechange s c thi hnh. y l nhng gi tr hp l cho thuc tnh readyState: Trng thi 0 1 2 3 4 M t Yu cu khng c khi ng Yu cu c ci t Yu cu c gi Yu cu ang c x l Yu cu hon tt
Chng ta s thm mt lnh If vo hm onreadystatechange kim tra phn hi ca chng ta hon tt hay cha (c ngha l chng ta c th nhn d liu ca chng ta):
xmlHttp.onreadystatechange = function() { if(xmlHttp.readyState == 4) { // Ly d liu t phn hi ca my ch
www.w3schools.com
} }
Thuc tnh responseText D liu c gi tr v t my ch c th c tip nhn vi thuc tnh responseText. Trong on m, chng ta s t gi tr ca trng vn bn "time" bng vi responseText:
xmlHttp.onreadystatechange=function() { if(xmlHttp.readyState==4) { document.myForm.time.value=xmlHttp.responseText; } }
www.w3schools.com
AJAX - Yu cu my ch
AJAX - Gi yu cu n my ch
gi ngm mt yu cu n my ch, chng ta s dng phng thc open() v send(). Phng thc open() nhn ba tham s. Tham s u tin nh ngha cch thc no c s dng khi gi yu cu (GET hoc POST). Tham s th hai ch ra ng dn ca tp tin m kch bn pha my ch. Tham s th ba ch ra yu cu c thc hin bt i xng hay khng. Phng thc send() gi ngm yu cu n my ch. Nu chng ta gi s rng tp tin HTML v ASP cng th mc, on m nh sau:
xmlHttp.open("GET","time.asp",true); xmlHttp.send(null);
By gi chng ta phi quyt nh khi no hm AJAX c thi hnh. Chng ta s hm ny chy "bn di mn hnh" khi ngi dng g vi ch trong trng vn bn username:
<form name="myForm"> Name: <input type="text" onkeyup="ajaxFunction();" name="username" /> Time: <input type="text" name="time" /> </form>
www.w3schools.com
try { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("Your browser does not support AJAX!"); return false; } } } xmlHttp.onreadystatechange = function() { if(xmlHttp.readyState == 4) { document.myForm.time.value = xmlHttp.responseText; } } xmlHttp.open("GET","time.asp",true); xmlHttp.send(null); } </script> <form name="myForm"> Name: <input type="text" onkeyup="ajaxFunction();" name="username" /> Time: <input type="text" name="time" /> </form> </body> </html>
www.w3schools.com
Ch : Thuc tnh Expires t thi lng (theo pht) m trang s c lu vng nh tm trn trnh duyt trc khi n qu hn. Nu ngi dng tr li cng trang trc khi n qu hn, phin bn c lu trong vng nh tm s c hin th. Response.Expires = -1 xc nh trang s khng bao gi c lu tm.
Name:
Time:
www.w3schools.com
V d AJAX Suggest
Chng ta va thy AJAX c s dng to ra cc ng dng tng tc mnh hn.
V d AJAX Suggest
Trong v d AJAX di y s minh ha cch mt trang web c th giao tip vi my ch web trc tuyn ngay ngi dng nhp d liu vo trong biu mu HTML.
G mt tn vo trong hp di y
First Name: Suggestions:
Nh bn thy n ch l mt biu mu HTML n gin vi mt trng nhp c gi l "txt1". Thuc tnh s kin ca trng ny nh ngha hm c by bi s kin onkeyup. on bn di biu mu cha mt vng c gi l "txtHint". Vng ny c s dng nh mt ni cha d liu c nhn v t my ch web. Khi ngi dng nhp d liu, mt hm gi l "showHint()" c thi hnh. Vic thi hnh ny c by bi s kin "onkeyup". Ni cch khc: Mi ln ngi dng di cc ngn tay ra khi phm bn trong trng nhp, hm showHint c gi.
function showHint(str) { if (str.length==0) { document.getElementById("txtHint").innerHTML=""; return; } xmlHttp=GetXmlHttpObject(); if (xmlHttp==null) { alert ("Your browser does not support AJAX!"); return; } var url = "gethint.asp"; url = url + "?q=" + str; url = url + "&sid=" + Math.random(); xmlHttp.onreadystatechange = stateChanged; xmlHttp.open("GET",url,true); xmlHttp.send(null); }
Hm ny thi hnh mi khi mt ch c nhp vo trng nhp. Nu c vi ch trong trng nhp (str.length > 0) hm ny thc hin nhng vic sau: nh ngha url (tn tp tin) gi n my ch Thm mt tham s (q) n url vi ni dung ca trng nhp Thm mt s ngu nhin trnh my ch s dng tp tin m To mt i tng XMLHTTP, v bo i tng thc hin hm gi l stateChanged khi mt thay i c by. M i tng XMLHTTP vi url cho. Gi mt yu cu HTTP n my ch Nu trng nhp rng, hm n gin l xa ni dung ca ni cha txtHint.
www.w3schools.com
Hm ny c kit k nh sau:
function GetXmlHttpObject() { var xmlHttp=null; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; }
Hm stateChanged() thc hin mi khi trng thi ca i tng XMLHTTP thay i. Khi trng thi i thnh 4 ("hon tt"), ni dung ca ni cha txtHint c in vi vn bn phn hi.
www.w3schools.com
M AJAX JavaScript
y l m JavaScript, lu tr trong tp tin "clienthint.js":
var xmlHttp function showHint(str) { if (str.length == 0) { document.getElementById("txtHint").innerHTML=""; return; } xmlHttp = GetXmlHttpObject(); if (xmlHttp == null) { alert("Your browser does not support AJAX!"); return; }
www.w3schools.com
var url = "gethint.asp"; url = url + "?q=" + str; url = url + "&sid=" + Math.random(); xmlHttp.onreadystatechange = stateChanged; xmlHttp.open("GET",url,true); xmlHttp.send(null); } function stateChanged() { if (xmlHttp.readyState == 4) { document.getElementById("txtHint").innerHTML=xmlHttp.responseText; } } function GetXmlHttpObject() { var xmlHttp = null; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; }
www.w3schools.com
V d ASP v AJAX
on m trong trang "gethint.asp" c vit trong VBScript cho Internet Information Server (IIS). N ch kim tra mt mng ca cc tn v tr v nhng tn tng ng n my khch:
<% response.expires = -1 dim a(30) 'in d liu cho mng vi nhng ci tn a(1) = "Anna" a(2) = "Brittany" a(3) = "Cinderella" a(4) = "Diana" a(5) = "Eva" a(6) = "Fiona" a(7) = "Gunda" a(8) = "Hege" a(9) = "Inga" a(10) = "Johanna" a(11) = "Kitty" a(12) = "Linda" a(13) = "Nina" a(14) = "Ophelia" a(15) = "Petunia" a(16) = "Amanda" a(17) = "Raquel" a(18) = "Cindy" a(19) = "Doris" a(20) = "Eve" a(21) = "Evita" a(22) = "Sunniva" a(23) = "Tove" a(24) = "Unni" a(25) = "Violet" a(26) = "Liza" a(27) = "Elizabeth" a(28) = "Ellen" a(29) = "Wenche" a(30) = "Vicky" 'ly tham s q t URL q = ucase(request.querystring("q")) 'tra tt c gi t mng nu di ca q > 0 if len(q) > 0 then hint = "" for i=1 to 30 if q = ucase(mid(a(i),1,len(q))) then if hint = "" then
www.w3schools.com
hint = a(i) else hint = hint & " , " & a(i) end if end if next end if 'xut "no suggestion" nu khng tm thy gi no hoc xut nhng gi tr ng if hint = "" then response.write("no suggestion") else response.write(hint) end if %>
V d PHP v AJAX
on m sau y c vit trong PHP. Ch : chy ton b v d trong PHP, nh i gi tr ca bin ng dn trong "clienthint.js" t "gethint.asp" thnh "gethint.php".
V d PHP
<?php header("Cache-Control: no-cache, must-revalidate"); // Date in the past header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Fill up array with names $a[] = "Anna"; $a[] = "Brittany"; $a[] = "Cinderella"; $a[] = "Diana"; $a[] = "Eva"; $a[] = "Fiona"; $a[] = "Gunda"; $a[] = "Hege"; $a[] = "Inga"; $a[] = "Johanna"; $a[] = "Kitty"; $a[] = "Linda"; $a[] = "Nina"; $a[] = "Ophelia"; $a[] = "Petunia"; $a[] = "Amanda"; $a[] = "Raquel";
www.w3schools.com
$a[] $a[] $a[] $a[] $a[] $a[] $a[] $a[] $a[] $a[] $a[] $a[] $a[]
= = = = = = = = = = = = =
"Cindy"; "Doris"; "Eve"; "Evita"; "Sunniva"; "Tove"; "Unni"; "Violet"; "Liza"; "Elizabeth"; "Ellen"; "Wenche"; "Vicky";
//ly tham s q t URL $q = $_GET["q"]; //tra tt c gi t mng nu di ca q > 0 if (strlen($q) > 0) { $hint = ""; for($i=0; $i<count($a); $i++) { if (strtolower($q) == strtolower(substr($a[$i],0,strlen($q)))) { if ($hint == "") { $hint = $a[$i]; } else { $hint = $hint . " , " . $a[$i]; } } } } // xut ra "no suggestion" nu khng tm thy gi hoc gi tr ng if ($hint == "") { $response = "no suggestion"; } else { $response = $hint; } //xut phn hi echo $response; ?>
www.w3schools.com
Chn mt tn trong hp bn di
Select a Customer: Customer info will be listed here.
Alfreds Futterkiste
Nh bn thy n ch l mt biu mu HTML n gin vi mt hp danh sch x xung gi l "customers". on bn di biu mu cha mt vng gi l "txtHint". Vng ny c dng lm ni cha thng tin nhn v t my ch web.
www.w3schools.com
Khi ngi dng chn d liu, hm "showCustomer()" c thi hnh. Vic thi hnh ca hm ny c by bi s kin "onchange". Ni cch khc: Mi khi ngi dng thay i gi tr trong hp x xung, hm showCustomer c gi. M JavaScript c lit k bn di.
M JavaScript AJAX
y l m JavaScript cha trong tp tin "selectcustomer.js":
var xmlHttp function showCustomer(str) { xmlHttp=GetXmlHttpObject(); if (xmlHttp==null) { alert ("Your browser does not support AJAX!"); return; } var url = "getcustomer.asp"; url = url+ "?q=" + str; url = url + "&sid=" + Math.random(); xmlHttp.onreadystatechange = stateChanged; xmlHttp.open("GET",url,true); xmlHttp.send(null); } function stateChanged() { if (xmlHttp.readyState == 4) { document.getElementById("txtHint").innerHTML = xmlHttp.responseText; } } function GetXmlHttpObject() { var xmlHttp = null; try { // Firefox, Opera 8.0+, Safari xmlHttp = new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
www.w3schools.com
Trang my ch AJAX
Trang my ch c gi bi JavaScript, l mt tp tin ASP n gin gi l "getcustomer.asp". Trang ny c vit trong VBScript cho Internet Information Server (IIS). N cng c vit d dng trong PHP, hoc mt vi ngn ng khc. M ny chy mt SQL n c s d liu v tr v kt qu nh mt bng biu HTML:
<% response.expires = -1 sql = "SELECT * FROM CUSTOMERS WHERE CUSTOMERID=" sql = sql & "'" & request.querystring("q") & "'" set conn = Server.CreateObject("ADODB.Connection") conn.Provider = "Microsoft.Jet.OLEDB.4.0" conn.Open(Server.Mappath("/db/northwind.mdb")) set rs = Server.CreateObject("ADODB.recordset") rs.Open sql, conn response.write("<table>") do until rs.EOF for each x in rs.Fields response.write("<tr><td><b>" & x.name & "</b></td>") response.write("<td>" & x.value & "</td></tr>") next rs.MoveNext loop response.write("</table>") %>
www.w3schools.com
V d AJAX XML
AJAX c th c dng giao tip vi tp tin XML.
V d AJAX XML
Trong v d AJAX bn di chng ta s minh ha cch mt trang web c th ly thng tin t mt tp tin XML bng cng ngh AJAX.
Chn mt CD trong hp bn di
Select a CD: CD info will be listed here.
Dolly Parton
Gii thch v d
V d trn cha mt biu mu HTML n gin v mt lin kt n JavaScript:
<html> <head> <script src="selectcd.js"></script> </head> <body> <form> Select a CD: <select name="cds" onchange="showCD(this.value)"> <option value="Bob Dylan">Bob Dylan</option> <option value="Bonnie Tyler">Bonnie Tyler</option> <option value="Dolly Parton">Dolly Parton</option> </select> </form> <p> <div id="txtHint"><b>CD info will be listed here.</b></div> </p> </body> </html>
Bn thy n ch l mt biu mu HTML n gin v mt hp x xung gi l "cds". on vn bn bn di biu mu cha mt vng gi l "txtHint". Vng ny c dng lu tr thng tin tip nhn t my ch.. Khi ngi dng chn d liu, hm "showCD" c thi hnh. Vic thi hnh ca hm ny c by bi s kin "onchange". Ni cch khc: Mi khi ngi dng thay i gi tr trong hp x xung, hm showCD c gi. www.w3schools.com Ngi dch: Hunh Dip Tn
M JavaScript AJAX
y l m JavaScript cha trong tp tin "selectcd.js":
var xmlHttp function showCD(str) { xmlHttp = GetXmlHttpObject(); if (xmlHttp == null) { alert ("Your browser does not support AJAX!"); return; } var url = "getcd.asp"; url = url + "?q=" + str; url = url + "&sid=" + Math.random(); xmlHttp.onreadystatechange = stateChanged; xmlHttp.open("GET",url,true); xmlHttp.send(null); } function stateChanged() { if (xmlHttp.readyState == 4) { document.getElementById("txtHint").innerHTML = xmlHttp.responseText; } } function GetXmlHttpObject() { var xmlHttp = null; try { // Firefox, Opera 8.0+, Safari xmlHttp = new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); }
www.w3schools.com
} return xmlHttp; }
Trang my ch AJAX
Trang my ch c gi bi JavaScript, l mt tp tin ASP n gin gi l "getcd.asp". Trang ny c vit trong VBScript cho Internet Information Server (IIS). N cng c vit d dng trong PHP, hoc mt vi ngn ng khc. M ny chy mt truy vn n tp XML v tr v kt qu dng HTML:
<% response.expires = -1 q=request.querystring("q") set xmlDoc = Server.CreateObject("Microsoft.XMLDOM") xmlDoc.async = "false" xmlDoc.load(Server.MapPath("cd_catalog.xml")) set nodes = xmlDoc.selectNodes("CATALOG/CD[ARTIST='" & q & "']") for each x in nodes for each y in x.childnodes response.write("<b>" & y.nodename & ":</b> ") response.write(y.text) response.write("<br />") next next %>
www.w3schools.com
V d v hi p XML AJAX
Trong khi responseText tr v phn hi HTTP nh mt chui, responseXML tr v phn hi nh mt XML. Thuc tnh ResponseXML tr v mt i tng ti liu XML, n c th c nhn din v tch bng cch dng cc phng thc v thuc tnh ca cu trc cy W3C DOM.
V d hi p AJAX ResponseXML
Trong v d AJAX sau y chng ta s minh ha cch mt trang c th ly thng tin t mt c s d liu bng cng ngh AJAX. Nhng d liu c chn t c s d liu ln ny s c chuyn i thnh mt ti liu XML, v sau chng ta s s dng DOM kt xut nhng gi tr hin th.
Chn tn trong hp di y
Select a Customer:
www.w3schools.com
V d trn cha mt biu mu HTML v mt hp x xung gi l "customers". Khi ngi dng chn mt khch hnh trong hp x xung, hm "showCustomer()" c thi hnh. Vic thi hnh ca hm ny c by bi s kin "onchange". Ni cch khc: Mi khi ngi dng thay i gi tr trong hp x xung, hm showCustomer() c gi. M JavaScript c lit k bn di.
M AJAX JavaScript
y l m JavaScript lu tr trong tp tin "selectcustomer_xml.js":
var xmlHttp function showCustomer(str) { xmlHttp=GetXmlHttpObject(); if (xmlHttp==null) { alert ("Your browser does not support AJAX!"); return; } var url = "getcustomer_xml.asp"; url = url + "?q=" + str; url = url + "&sid=" + Math.random(); xmlHttp.onreadystatechange = stateChanged; xmlHttp.open("GET",url,true); xmlHttp.send(null); } function stateChanged() { if (xmlHttp.readyState==4) { var xmlDoc = xmlHttp.responseXML.documentElement; document.getElementById("companyname").innerHTML= xmlDoc.getElementsByTagName("compname")[0].childNodes[0].nodeValue; document.getElementById("contactname").innerHTML= xmlDoc.getElementsByTagName("contname")[0].childNodes[0].nodeValue; document.getElementById("address").innerHTML= xmlDoc.getElementsByTagName("address")[0].childNodes[0].nodeValue; document.getElementById("city").innerHTML= xmlDoc.getElementsByTagName("city")[0].childNodes[0].nodeValue; document.getElementById("country").innerHTML= xmlDoc.getElementsByTagName("country")[0].childNodes[0].nodeValue; } } function GetXmlHttpObject() {
www.w3schools.com
var xmlHttp=null; try { // Firefox, Opera 8.0+, Safari xmlHttp = new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; }
Cc hm showCustomer() v GetXmlHttpObject() trn ging nh cc phn trc. Hm stateChanged() cng c cp trc y, tuy nhin; ln ny chng ta tr v kt qu l ti liu XML (vi responseXML) v s dng DOM kt xut cc gi tr hin th.
Trang my ch AJAX
Trang my ch c gi bi JavaScript, l mt tp tin ASP n gin gi l "getcustomer_xml.asp". Trang ny c vit trong VBScript cho Internet Information Server (IIS). N cng c vit d dng trong PHP, hoc mt vi ngn ng khc. M ny chy mt truy vn SQL n c s d liu v tr v kt qu l mt ti liu XML:
<% response.expires = -1 response.contenttype = "text/xml" sql = "SELECT * FROM CUSTOMERS " sql = sql & " WHERE CUSTOMERID='" & request.querystring("q") & "'" on error resume next set conn = Server.CreateObject("ADODB.Connection") conn.Provider = "Microsoft.Jet.OLEDB.4.0" conn.Open(Server.Mappath("/db/northwind.mdb")) set rs = Server.CreateObject("ADODB.recordset") rs.Open sql, conn if err <> 0 then
www.w3schools.com
response.write(err.description) set rs = nothing set conn = nothing else response.write("<?xml version='1.0' encoding='ISO-8859-1'?>") response.write("<company>") response.write("<compname>" &rs.fields("companyname")& "</compname>") response.write("<contname>" &rs.fields("contactname")& "</contname>") response.write("<address>" &rs.fields("address")& "</address>") response.write("<city>" &rs.fields("city")& "</city>") response.write("<country>" &rs.fields("country")& "</country>") response.write("</company>") end if on error goto 0 %>
dng th hai trong m ASP trn: response.contenttype="text/xml". Thuc tnh ContentType t kiu ni dung HTTP cho i tng hi p. Gi tr mc nh cho thuc tnh ny l "text/html". Ln ny chng ta mun kiu ni dung l XML. Sau khi chn d liu t c s d liu, chng ta xy dng mt ti liu XML vi d liu nhn c.
www.w3schools.com