這裡用到的是dojo 原裝的jsonp技術 dojo.io.script.get
項目訪問的後台是已經成型的ssi架構action,前端是一個mobile頁面。
<!DOCTYPE HTML> <html> <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no"/><link rel="stylesheet" type="text/css" href="demo.css"/><link rel="stylesheet" href="libs/dojo/dojox/mobile/themes/android/android.css" type="text/css" media="screen" title="no title" charset="utf-8"><script src="http://ajax.googleapis.com/ajax/libs/dojo/1.9.1/dojo/dojo.js" data-dojo-config="async:true"></script></script> <script> require(["dojox/mobile/parser", "dojox/mobile/deviceTheme", "dojox/mobile/compat", "dojox/mobile","dojox/mobile/TextBox","dojox/mobile/Button" ],function(parser, deviceTheme) { // Parse the page for widgets!parser.parse();}); </script> <head> <title>PhoneGap Test</title> </head> <body><!-- ACCIDENT TOOLKIT PAGE --><div dojoType="dojox.mobile.View" id="accHelp" selected="true"> <h1 dojoType="dojox.mobile.Heading">登入頁面</h1> <ul dojoType="dojox.mobile.RoundRectList"> <li dojoType="dojox.mobile.ListItem" ><label>Username</label><input id="username" class="mblTextBox" type="text" data-dojo-type="dojox.mobile.TextBox"></li> <li dojoType="dojox.mobile.ListItem" ><label>Password</label><input id="password" class="mblTextBox" type="password" data-dojo-type="dojox.mobile.TextBox"></li><button id="resetBtn" class="baseBtn orangeBtn" dojoType="dojox.mobile.Button" type="submit" onClick="itemClicked();"> Reset Form</button><h2 dojoType="dojox.mobile.RoundRectCategory" id="loginResult"></h2> </ul></div><!-- EXCHANGE DRIVER INFO PAGE --><script>function itemClicked() { var userName = dojo.byId("username").value + ":" + dojo.byId("password").value ; var url = "http://192.168.0.20:8080/igsys/mobilelogin.action"; login(url);}function login(url){require(["dojo/io/script", "dojo/dom", "dojo/_base/array", "dojo/domReady!"], function(){ //first do the io script request //make the request just as beforedojo.io.script.get({url: url,callbackParamName: "callback",content: { userName: "admin:123456", password: "123456"}, load: function (data) { console.log('OK', data.result);if(data.result=="200"){dojo.byId("username").innerHTML = "登入成功";location.href='loginResult.html';}else dojo.byId("loginResult").innerHTML = "登入失敗"; }, error: function(error) { console.log('Error', error); }}); }); }</script></body> </html>
背景mobilelogin.action只要添加兩行代碼即可
String callback = this.getRequest().getParameter("callback"); String jsoncallback = callback + "({'result':"+result+"})"; PrintWriter out = this.getResponse().getWriter(); out.print(jsoncallback); out.flush(); out.close();前端的參數傳遞通過傳統的String sysUserName = this.getRequest().getParameter("userName")擷取。
這裡有必要解釋一下,jsonp跨域訪問,會在http://xxxx.action後面預設加上callback參數值,這個相當於一個sessionId一樣。
而傳回值result可以通過html的data直接擷取.這樣一來,就可以實現json資料的返回了。