在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     }

转载于:https://www.cnblogs.com/AUOONG/archive/2012/04/20/2459226.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值