一、处理数据:

 将一些数据发送到服务器并接收响应 【post请求】

<label>Your name: 
  <input type="text" id="ajaxTextbox" />
</label>
<span id="ajaxButton" style="cursor: pointer; text-decoration: underline">
  Make a request
</span>

//1、步骤
 document.getElementById("ajaxButton").onclick = function() { 
      var userName = document.getElementById("ajaxTextbox").value;
   //
      makeRequest('test.php',userName); 
  };

//2、发送请求
 function makeRequest(url, userName) {

    ...

    httpRequest.onreadystatechange = alertContents;
//POST请求,
    httpRequest.open('POST', url);
//
    httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
 //将数据作为参数 包含在对的调用中http...send()
    httpRequest.send('userName=' + encodeURIComponent(userName));
  }

//3、响应处理
function alertContents() {
  if (httpRequest.readyState === XMLHttpRequest.DONE) {
    if (httpRequest.status === 200) {
//
      var response = JSON.parse(httpRequest.responseText);
      alert(response.computedString);
    } else {
      alert('There was a problem with the request.');
    }
  }
}

 

二、定时XHR例子:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>XHR log time</title>
    <style>

    </style>
  </head>
  <body>
    <p id="writeData" class="data">Off-Line</p>
    <p id="lastStamp">No Data yet</p>

    <script>

    const fullData = document.getElementById('writeData');
    const lastData = document.getElementById('lastStamp');

    function fetchData() {
      console.log('Fetching updated data.');
       //1、发出请求
      let xhr = new XMLHttpRequest();
      // 2、发出实际请求
      xhr.open("GET", "time-log.txt", true);
      // 3、 
      xhr.onload = function() {
     //
        updateDisplay(xhr.response);
      }
      xhr.send();
    }

    function updateDisplay(text) {
//
      fullData.textContent = text;
//
      let timeArray = text.split('\n');
      //
      if(timeArray[timeArray.length-1] === '') {
//
        timeArray.pop();
      }
//
      lastData.textContent = timeArray[timeArray.length-1];
    }
  //电话每5秒重复一次
    setInterval(fetchData, 5000);
    </script>
  </body>
</html>

 

 posted on 2020-12-01 18:07  楼顶铁板烧  阅读(106)  评论(0编辑  收藏  举报