1. 程式人生 > 實用技巧 >ajax _02【XML響應,post請求】

ajax _02【XML響應,post請求】

一、處理資料:

將一些資料傳送到伺服器並接收響應 【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>