標籤:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>修改內容</title> 6 <!-- 7 所有現代瀏覽器均支援XMLHttpRequest對象(IE6 IE5使用ActiveXObject) 8 XMLHttpRequest用於在後台與伺服器交換資料,這意味著可以在不重新載入整個網頁的情況下,對網頁的某部分進行更新 9 建立XMLHttpRequest對象10 IE7+ FireFox chrome Opera Safari11 xmlhttp = new XMLHttpRequest();12 IE5 IE613 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");14 15 -->16 <script>17 function loadXMLDoc() {18 var xmlhttp;19 if (window.XMLHttpRequest) {20 //code for IE7+ FireFox chrome Opera Safari21 xmlhttp = new XMLHttpRequest();22 } else {23 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");24 }25 /**26 * 當使用async=true時,請規定在想贏處於onreadystatechange事件中的就緒狀態時執行的函數27 * 如果async=false時就不必使用onreadystatechange函數,將代碼放到send()語句之後即可28 * xmlhttp.open("GET","ajax_info.txt",false);29 *xmlhttp.send();30 *document.getElementById("myDiv").innerHTML=xmlhttp.responseText;31 * */32 xmlhttp.onreadystatechange = function () {33 if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {34 document.getElementById("myDiv").innerHTML = xmlhttp.responseText;35 }36 }37 //open(method,url,async):38 //method :規定請求的類型 GET或POST39 //url : 檔案在伺服器上的位置40 //async:true為非同步 false為同步41 xmlhttp.open("GET", "../ajax_info.txt", true);42 //send(string)將請求發送到伺服器 帶有string參數的僅用於POST請求43 /**44 * 與POST想比GET更簡單也更快,並且在大部分情況下都能使用45 * 然而在以下情況下請使用POST請求:46 * 無法使用快取檔案(補救伺服器上的檔案或資料庫)47 * 向伺服器發送大量資料(POST沒有資料量限制)48 * 發送包含未知字元的使用者輸入時POST比GET更穩定也更可靠49 * 使用POST請求時如果需要HTML表單那樣POST資料,請使用setRequestHeader()來添加HTTP頭然後在send()方法中規定希望發送的資料50 * xmlhttp.open("POST","ajax_test.html",true);51 *xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");52 *xmlhttp.send("fname=Henry&lname=Ford");53 * sendRequestHeader(header,value) header:規定頭的名稱 value:規定頭的值54 *55 * */56 57 xmlhttp.send();58 59 }60 </script>61 </head>62 <body>63 <div id="myDiv">64 <h2>使用Ajax修改該文本的內容</h2>65 </div>66 <button type="button" onclick="loadXMLDoc()">修改內容</button>67 </body>68 </html>
[AJAX系列]XMLHttpRequest請求