zoukankan      html  css  js  c++  java
  • 在openwrt中使用Post方式异步提交数据

    在openwrt中,大部分都是使用get方式来进行数据交互,如:XHR.get,XHR.poll。我们可以通过查看xhr.js的源代码来看他的具体实现逻辑。通过查看源代码可以知道,get/poll都是XHR的静态方法,而具体的内部逻辑中,还是通过new XHR().get来进行的数据请求。因此我们也可以使用这种方式来调用他内部提供的post方法。

    在使用post方法来交互数据时,对于回调函数中仅有的一个参数是一个xhr对象,因此要获取返回的数据需要调用responseText属性。

     1 <%
     2      local h = require "luci.http"
     3  
     4      if h.formvalue('act') == 'query' then
     5          h.write('data string...')
     6          return
     7      end
     8  %>
     9  <input type="button" value="query" onclick="queryHandler(this)" />
    10  <script type="text/javascript" src="<%=resource%>/xhr.js"></script>
    11  <script type="text/javascript">
    12  // <![CDATA[
    13      function queryHandler() {
    14          new XHR().post('<%=REQUEST_URI%>', {
    15              act : 'query'
    16          }, function(xhr) {
    17              // 获取到的返回数据,这里与get返回的数据不一样,这里是字符串,而get方式回来的是json
    18              console.log(xhr.responseText);
    19          })
    20      }
    21  // ]]>
    22  </script>

    正如示例中所描述的,对于post回来的数据,我们通过responseText所得到的是一个字符串,如果我们也想如同get方式回来的是json格式的数据,那么我们可以将xhr.js中get的实现拿过来。

     1     function queryHandler() {
     2         new XHR().post('<%=REQUEST_URI%>', {
     3             act : 'query'
     4         }, function(xhr) {
     5             var json = null;
     6             if (xhr.getResponseHeader("Content-Type") == "application/json") {
     7                 try {
     8                     json = eval('(' + xhr.responseText + ')');
     9                 }
    10                 catch(e) {
    11                     json = null;
    12                 }
    13             }
    14 
    15             // 获取的数据
    16             console.log(json);
    17         })
    18     }
  • 相关阅读:
    CAP 与数据一致性
    C++的构造函数为何不能为虚函数
    构造函数和析构函数中可以调用调用虚函数吗
    HTTP状态码
    C++ 单例模式实现
    【转】十大经典排序算法
    C++ short/int/long/long long 等数据类型大小
    块/文件/对象三种存储的优缺点
    罗振宇《时间的朋友》2019-2020
    Google Hacking
  • 原文地址:https://www.cnblogs.com/AUOONG/p/2459226.html
Copyright © 2011-2022 走看看