struts2+js重构的Ajax示例,struts2+jquery重构的Ajax示例
jquery毕竟是包装了JS不少用法的一个对象,虽原理相同,但用法更简易,所以就不多说了,jQuery_ajax(url, onload, onerror, method, params, dataType)是个人包装了jquery的ajax()方法的简易重构方法,可在我的博客下载整个案例。
测试页index.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>integration test</title> <script type="text/javascript" src="js/jquery-1.8.3.js"></script> <script type="text/javascript" src="js/jQuery-Ajax-Restructure.js"></script> <script type="text/javascript" src="js/EventHandler.js"></script> <script type="text/javascript" src="js/js-Ajax-Restructure.js"> </script> <!-- <script type="text/javascript"> $(function() { $("#send").click(function() { jQuery_ajax("login", function (data,textStatus){ alert("msg:" + data.msg + "\nusername:" + data.user["username"] + "\npassword:"+data.user["password"]); }, null, null, $("#myform").serialize(), "json"); }); }) </script> --> </head> <body> <form id="myform" method="post"> <label for="username">用户名:</label> <input id="username" placeholder="请输入你的用户名" name="user.username" type="text"/><br> <label for="password">密码:</label> <input id="password" placeholder="请输入你的密码" name="user.password" type="password"/><br> <input id="send" type="button" value="登录"> </form> <hr> <script type="text/javascript"> var btn = document.getElementById("send"); EventUtil.addHandler(btn, "click", function(event){ //跨浏览器对象绑定事件(DOM元素初始化后调用有效,放在form前调用无效) var user = "user.username="+document.getElementById("username").value; var pass = "user.password="+document.getElementById("password").value; var params = user+"&"+pass; new net.AjaxRequest("login", function (){ var data = JSON.parse(this.req.responseText); alert("msg:"+data.msg+"\nusername:"+data.user.username+"\npassword:"+data.user.password); }, null, "POST", params); }); </script> </body> </html>
JS重构代码js/js-Ajax-Restructure.js(上述JS获取表单方式有些麻烦,要是对JS追求比较高的可以定义一个表单序列化函数而无需逐个获取)
/* * @author:Wilson<br> * @Date:2016/12/4 */ var net = new Object(); // AjaxRequest constructed function net.AjaxRequest = function(url, onload, onerror, method, params) { this.req = null; this.onload = onload; this.onerror = (onerror) ? onerror : this.defaultError; this.loadDate(url, method, params); } // Init XMLHttpRequest,then send request according to the param "method" net.AjaxRequest.prototype.loadDate = function(url, method, params) { if (window.XMLHttpRequest) { this.req = new XMLHttpRequest(); } else if (window.ActiveXObject) { try { this.req = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { this.req = new ActiveXObject("Miscrosoft.XMLHTTP"); } catch (e) { alert("请求对象构建失败"); } } } var flag = (!method || method.toUpperCase() != "POST" ? true : false); if (flag) { url = url + "?" + params; } if (this.req) { try { var loader = this; this.req.onreadystatechange = function() { net.AjaxRequest.onReadyState.call(loader); } this.req.open(flag?"GET":"POST", url, true); if (!flag) { this.req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); this.req.send(params); } else { this.req.send(null); } } catch (err) { this.onerror.call(this); } } } // Callback function net.AjaxRequest.onReadyState = function() { var req = this.req; var ready = req.readyState; if (ready == 4) if (req.status == 200) { this.onload.call(this); } else { this.onerror.call(this); } } // Default error processing function net.Ajax.prototype.defaultError = function() { alert("错误数据\n\n 回调状态:" + this.req.readyState + "\n状态:" + this.req.status) }
逻辑层LoginTestAction.java
package org.wilson.action; import org.wilson.vo.User; import com.opensymphony.xwork2.ActionSupport; @SuppressWarnings("serial") public class LoginTestAction extends ActionSupport { private User user; private String msg; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } @Override public String execute() throws Exception { System.out.println(user.getUsername()); System.out.println(user.getPassword()); this.msg = "struts2完成"; return SUCCESS; } }VO层User.java
package org.wilson.vo; public class User { private String username; private String password; public User() { } public User(String username, String password) { super(); this.username = username; this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }struts.xml配置(记得插入struts2-json-plugin-2.x.xx.x.jar包)
<package name="ajax" extends="json-default"> <action name="login" class="org.wilson.action.LoginTestAction"> <result type="json"></result> </action> </package>js/jQuery-Ajax-Restructure.js
/* * @author:Wilson<br> * @Date:2016/12/4 */ // Ajax Restructure function jQuery_ajax(url, onload, onerror, method, params, dataType) { var flag = (!method || method.toUpperCase() != "POST" ? true : false); $.ajax({ url : flag ? (url + "?" + params) : url, success : onload ? onload : function(responseText, status) { alert(responseText); }, type : flag ? "GET" : "POST", data : flag ? null : params, dataType : dataType ? dataType : "text", error : onerror ? onerror : function(XMLHttpRequest, textStatus, errorThrown) { alert("请求失败"); } }); }
注:jquery的serialize()序列化表单方法和js的传参是字符串格式"arg0=val0&arg1=val1..."而非JSON格式,依然会被解析传值到struts的参数中,但struts的回应值类型都是JSON,访问JSON值可以先用JSON对象的parse()方法解析为JS对象,也可以通过上述jquery回调函数中的"data.msg"格式访问