1先把函數擺出來:
function loadXMLDoc() {
//步驟1. 創建XMLHttpRequest異步對象
var xmlhttp;
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari 瀏覽器執行代碼
xmlhttp = new XMLHttpRequest();
}
else {
// IE6, IE5 瀏覽器執行代碼
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//步驟2. 設置回調函數
xmlhttp.onreadystatechange = function () {
//步驟5. 在回調函數中針對不同的響應狀態進行處理
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log(xmlhttp.responseText + "獲取結束")
}
}
//步驟3. 使用open方法與服務器建立連接
xmlhttp.open("GET", "/package.json", true);
//步驟4. 向服務器發送數據
xmlhttp.send();
// post 需要傳遞參數
// xhr.send("name=jay&age=18")
}
2測試:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
function loadXMLDoc() {
//步驟1. 創建XMLHttpRequest異步對象
var xmlhttp;
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari 瀏覽器執行代碼
xmlhttp = new XMLHttpRequest();
}
else {
// IE6, IE5 瀏覽器執行代碼
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//步驟2. 設置回調函數
xmlhttp.onreadystatechange = function () {
//步驟5. 在回調函數中針對不同的響應狀態進行處理
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log(xmlhttp.responseText + "獲取結束")
}
}
//步驟3. 使用open方法與服務器建立連接
xmlhttp.open("GET", "/package.json", true);
//步驟4. 向服務器發送數據
xmlhttp.send();
// post 需要傳遞參數
// xhr.send("name=jay&age=18")
}
</script>
</head>
<body>
<button type="button" onclick="loadXMLDoc()">修改內容</button>
</body>
</html>
3結果