JavaScript Ajax 實現

wdapp發表於2020-02-03

Ajax.js 示例程式碼

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<input type="text" id="test-ie-response-text">
<script>
var request;
if (window.XMLHttpRequest) {
  request = new XMLHttpRequest();
} else {
  request = new ActiveXObject('Microsoft.XMLHTTP'); // 新建Microsoft.XMLHTTP物件
}

function success(text) {
  var textarea = document.getElementById("test-ie-response-text");
  textarea.value = text;
}

function fail(code) {
  var textarea = document.getElementById("test-ie-response-text");
  textarea.value = "Error code: " + code;
}

request.onreadystatechange = function() { // 狀態發生變化時,函式被回撥
  if (request.readyState === 4) { // 成功完成
    // 判斷響應結果:
    if (request.status === 200) {
      // 成功,通過responseText拿到響應的文字:
      return success(request.responseText);
    } else {
      // 失敗,根據響應碼判斷失敗原因:
      return fail(request.status);
    }
  } else {
    // HTTP請求還在繼續...
  }
};

// 傳送請求:
request.open("GET", "./index.json");
request.send();

</script>
</body>
</html>

複製程式碼

index.json檔案內容

{
  "data": {
    "name": "hello world"
  }
}

複製程式碼

相關文章