1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<html> <head> <script
type= "text/javascript" src= "/jquery/jquery.js" ></script> <script
type= "text/javascript" > $(document).ready( function (){ $( "#bt1" ).click( function (){ htmlobj=$.ajax({url: "/jquery/test1.txt" ,async: false }); $( "#myDiv" ).html(htmlobj.responseText); }); }); </script> </head> <body> <div
id= "myDiv" >abcdefg</div> <button
id= "bt1" type= "button" >change
abcdefg</button> </body> </html> |
2:通過 AJAX,您的 JavaScript 可使用 JavaScript 的 XMLHttpRequest 對象來直接與服務器進行通信。通過這個對象,您的 JavaScript 可在不重載頁面的情況與 Web 服務器交換數據。AJAX 在瀏覽器與 Web 服務器之間使用異步數據傳輸(HTTP 請求),這樣就可使網頁從服務器請求少量的信息,而不是整個頁面。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
<script
type= "text/javascript" > function loadXMLDoc() { var xmlhttp; var txt,x,i; if (window.XMLHttpRequest) { //
code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp= new XMLHttpRequest(); } else { //
code for IE6, IE5 xmlhttp= new ActiveXObject( "Microsoft.XMLHTTP" ); } xmlhttp.onreadystatechange= function (){ if (xmlhttp.readyState==4
&& xmlhttp.status==200) {
xmlDoc=xmlhttp.responseXML; txt= "" ; x=xmlDoc.getElementsByTagName( "title" ); for (i=0;i<x.length;i++) { txt=txt
+ x[i].childNodes[0].nodeValue + "<br
/>" ; } document.getElementById( "myDiv" ).innerHTML=txt; } } xmlhttp.open( "GET" , "/example/xmle/books.xml" , true ); xmlhttp.send(); } </script>
e:當請求被髮送到服務器時,我們需要執行一些基於響應的任務。每當 readyState 改變時,就會觸發 onreadystatechange 事件。readyState 屬性存有 XMLHttpRequest 的狀態信息。下面是 XMLHttpRequest 對象的三個重要的屬性:
在 onreadystatechange 事件中,我們規定當服務器響應已做好被處理的準備時所執行的任務。 當 readyState 等於 4 且狀態爲 200 時,表示響應已就緒: xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } 4:callback(回調) 函數是一種以參數形式傳遞給另一個函數的函數。 核心代碼:
|