首先来写login.html
<!DOCTYPEhtml> <html> <head> <title>prictice.html</title> <Metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/> <linkrel="stylesheet"href="jquery.mobile-1.4.5/jquery.mobile-1.4.5.css"> <scriptsrc="js/jquery-1.9.1.js"></script> <scripttype="text/javascript"src="jquery.mobile-1.4.5/jquery.mobile-1.4.5.js"></script> <scripttype="text/javascript"src="js/login.js"></script> </head> <body> <divdata-role="head"></div> <divdata-role="content"> <divstyle="text-align:center;"> <imgsrc="image/grid_knowledge.png"alt="logo"/> </div> <div> <span>用户名:</span><inputid="username"type="text"> <sapn>密码:</sapn><inputid="password"type="password"> <divdata-role="controlgroup"data-type="horizontal"style="text-align:center;"> <buttonid="login"inline="true">登陆</button> <buttonid="regist"inline="true">注册</button> </div> </div> </div> <divdata-role="footer"data-position="fixed"style="text-align:center;">版本</div> </body> </html>
然后来看下login.js
$(function(){ $.support.cors=true; $.mobile.allowCrossDomainPages=true; $('#login').click(function(){ varuserName=$('#username').val(); varpasswd=$('#password').val(); //alert(userName+""+passwd); $.ajax({ type:"POST",url:"http://127。0.0.1:8080/sfw/testjsonp",dataType:"jsonp",//这里是重点 jsonp:"callback",//这里是重点 jsonpCallback:"handler",//这里是重点 //context:this,contentType:"application/json;charset=UTF-8",data:{username:userName,passwd:passwd},async:true,success:function(data){ alert("loginsuccess!"); //$(this).alert("3333"); } }); functionhandler(data){//回调函数 alert("good"); } }) })
再看下struts配置
<packagename="json"extends="json-default"> <actionname="testjsonp"class="cn.framework.action.TestJsonp"method="testAction"> <resulttype="json"> </result> </action> </package>
最后看下action
packagecn.framework.action; importjava.io.IOException; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; importorg.apache.struts2.ServletActionContext; publicclassTestJsonpextendsBaseAction{ privatestaticfinallongserialVersionUID=1L; publicStringtestAction(){ HttpServletRequestrequest=ServletActionContext.getRequest(); HttpServletResponseres=ServletActionContext.getResponse(); Stringusername=request.getParameter("username"); Stringpassword=request.getParameter("passwd"); Stringfunc=request.getParameter("callback"); System.out.println("username:"+username+"password:"+password); StringBuffers=newStringBuffer(); s.append(func); s.append("({\"username\":\""); s.append(username); s.append("\","); s.append("\"password\":\""); s.append(password); s.append("\"})"); try{ res.getWriter().write(s.toString()); res.getWriter().flush(); }catch(IOExceptione){ e.printStackTrace(); } returnnull; } }
总结:有二点需要注意,一个是js中的dataType,还有jsonp的属性。另一个是返回的json数据的格式是一个带json数据的方法名handler({"username":"aaa","password","bbb"})