这里用到的是dojo 原装的jsonp技术 dojo.io.script.get
项目访问的后台是已经成型的ssi框架action,前端是一个mobile页面。
@H_404_18@ <!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 before dojo.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数据的返回了。