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