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>
  • 相关阅读:
    爬虫工具简单整理
    vue单页面处理SEO问题
    深入浅出MyBatis-快速入门
    js的匿名函数 和普通函数
    Javascript位置 body之前、后执行顺序!
    eclipse中的ctrl+H使用中的问题
    Eclipse中ctrl+shift+r与ctrl+shift+t的区别
    Java 判断字符串是否为空的四种方法、优缺点与注意事项
    eclipse 快捷键
    只缩进新加一段代码的方法
  • 原文地址:https://www.cnblogs.com/a1-top/p/14069877.html
Copyright © 2011-2022 走看看