Ajax

  1. Create XMLHttpRequest(XHR) Object
  2. Create callback function
  3. Open request
  4. Send request

sample

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <link href='//fonts.googleapis.com/css?family=Varela+Round' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" href="css/main.css">
  <title>AJAX with JavaScript</title>
  <script>
    var xhr = new XMLHttpRequest();  //Create XMLHttpRequest(XHR) Object
    //Create callback function
    xhr.onreadystatechange = function(){
      if(xhr.readyState === 4){
        document.getElementById("ajax").innerHTML = xhr.responseText;
      }
    };
    xhr.open('GET', 'sidebar.html'); //Open request
    function ajax(){ 
      xhr.send(); //send
      document.getElementById("ajax-btn").style.display = "none";
    }
  </script>
</head>
<body>
  <div class="grid-container centered">
    <div class="grid-100">
      <div class="contained">
        <div class="grid-100">
          <div class="heading">
            <h1>Bring on the AJAX</h1>
          </div>
          <div id="ajax">
            <button id="ajax-btn" onclick="ajax()">Show</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>
</html>

如果使用jquery...

$("#ajax").load('sidebar.html')

這樣她就會把sidebar讀進前面你給他的id裡,就等於開頭的那四個步驟

onreadystatechange

每當readyState改變的時候都會觸發onreadystatechange,有四種狀態

0 request未初始化

1 server連結已建立

2 request已接收

3 request處理中

4 request已完成,且respond已建立 所以上面才會有xhr.readyState === 4

Status

只靠readyState去判斷狀態有時候可能會碰上問題,比方網頁可能已經不在了 所以可以增加status判斷

if(xhr.status === 200)

Json

雖然長得和javascript的object很像,但需要使用雙引號"name": "telsa"

讀取josn資料更新網頁

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
  if (xhr.readyState === 4 ){
    //console.log(xhr.responseText);
    var employees = JSON.parse(xhr.responseText); //把json轉成javascript object
    var html = '<ul class="bulleted">';
    for(var i=0; i<employees.length; i++){
      if (employees[i].inoffice === true) {
        html += '<li class="in">';
      } else {
        html += '<li class="out">';
      }
      html += employees[i].name;
      html += '</li>';
    }
    html += '</ul>';
    console.log(html);
    document.getElementById("employeeList").innerHTML = html;

  }
};

xhr.open('GET','data/employees.json');
xhr.send();

results matching ""

    No results matching ""