zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    Echarts图表 相关技术点
    Jquery off() on() data()
    Js 正则表达式
    Java jar项目获取配置文件的项
    Java String.split 的坑,会忽略空值
    C# 工作流 状态机 门控制
    二维码SDK,高效率,高识别率,甩zxing,zbar几条街
    C#文本转语音,可导出在本地mp3或者wav文件
    api接口签名验证(MD5)
    C# 站点IP访问频率限制 针对单个站点的实现方法
  • 原文地址:https://www.cnblogs.com/a1-top/p/14069877.html
Copyright © 2011-2022 走看看