phonegap-connection
既存のdemoに基づいてjqueryがhttpリクエストをコミットし,データを返すjson解析を追加した.jqueryは何年もよく知らないので、急いで復習しなければならないようです.
index.html
TestServlet.JAvaはservletとテスト用に書いてありますが、別の実装ができます.
index.html
<script type="text/javascript" charset="utf-8" src="jquery-1.8.1.min.js"></script>
<script type="text/javascript" charset="utf-8" src="cordova-2.0.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is loaded and it is now safe to make calls Cordova methods
//
function onDeviceReady() {
checkConnection();
}
function checkConnection() {
var networkState = navigator.network.connection.type;
var states = {};
states[Connection.UNKNOWN] = 'Unknown connection';
states[Connection.ETHERNET] = 'Ethernet connection';
states[Connection.WIFI] = 'WiFi connection';
states[Connection.CELL_2G] = 'Cell 2G connection';
states[Connection.CELL_3G] = 'Cell 3G connection';
states[Connection.CELL_4G] = 'Cell 4G connection';
states[Connection.NONE] = 'No network connection';
// alert('Connection type: ' + states[networkState]+data);
}
$.get("http://192.168.0.100:8080/testserver/TestServlet", function(data) {
var dataObj=eval("("+data+")");// json
//if(dataObj.rows.length == 0) return;
$.each(dataObj.rows,function(idx,item){
//alert(item.item1+",value:"+item.item2);
$("#msg").append("<li>item1:" + item.item1+ " item2:" + item.item2+ "</li>");
});
});
</script>
TestServlet.JAvaはservletとテスト用に書いてありますが、別の実装ができます.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//
JSONObject jsonObj = new JSONObject();
JSONArray jsonArr = new JSONArray();
JSONObject jsonObjArr = new JSONObject();
JSONObject jsonObjArr1 = new JSONObject();
try {
jsonObjArr.put("item1", "a");
jsonObjArr.put("item2", "b");
jsonArr.put(jsonObjArr);
jsonObjArr1.put("item1", "c");
jsonObjArr1.put("item2", "d");
jsonArr.put(jsonObjArr1);
jsonObj.put("rows", jsonArr);
System.out.println(jsonObj.toString());
//{"rows":[{"item2":"b","item1":"a"},{"item2":"d","item1":"c"}]}
out.print(jsonObj.toString());
out.close();
} catch (JSONException e) {
e.printStackTrace();
}
}