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