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>
  • 相关阅读:
    Importing multi-valued field into Solr from mySQL using Solr Data Import Handler
    VMware Workstation 虚拟机使用无线wifi上网配置
    Linux开发黑客
    GitHub 使用说明
    虹软人脸检测和识别C#
    C#将结构体和指针互转的方法
    笔记本电脑连接wifi,同时提供热点wifi给手机使用
    基于STM32L4的开源NBIOT开发资料
    ESP8266擦除工具完整安装
    开发快平台(M302I小e开发板系列教程)
  • 原文地址:https://www.cnblogs.com/a1-top/p/14069877.html
Copyright © 2011-2022 走看看