• 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('
    ');
          //
          if(timeArray[timeArray.length-1] === '') {
    //
            timeArray.pop();
          }
    //
          lastData.textContent = timeArray[timeArray.length-1];
        }
      //电话每5秒重复一次
        setInterval(fetchData, 5000);
        </script>
      </body>
    </html>
  • 相关阅读:
    实现停车记录
    Python第四章__装饰器、迭代器
    请问使用jmeter在tcp取样器测试中服务器名称或ip,端口可以填变量值吗?
    [drp 7]转发和重定向的区别
    [drp 6]接口和抽象类的区别,及其应用场景
    MongoDB 3: 使用中的问题,及其应用场景
    MongoDB 2: 安装和使用
    MongoDB 1: NoSQL 和 SQL的区别
    Redis 2:简单使用
    Redis 1:简介
  • 原文地址:https://www.cnblogs.com/a1-top/p/14069877.html
Copyright © 2020-2023  润新知