Struts ajax json重新整理
刚才写的例子,出了些问题,又重新写了一个。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Login Page</title> <script type="text/javascript" src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript" src="jquery.validate.min.js"></script> <script> $.validator.setDefaults({ submitHandler: function() { var params=$("input").serialize(); $.ajax({ method:"post", url:"json.action", data:params, dataType:"json", success:function(data){ console.log(data.username); }, error:function(){ console.log("error"); } }); } }); $().ready(function() { $("#loginForm").validate({ rules: { username: { required: true, minlength: 2 }, password: { required: true, minlength: 5 } }, messages: { username: { required: "请输入用户名", minlength: "用户名必需由两个字母组成" }, password: { required: "请输入密码", minlength: "密码长度不能小于 5 个字母" } } }); }); </script> </head> <body> <form action="#" method="post" id="loginForm"> UserName: <input type="text" name="username" id="username" /> <br/> Password:<input type="password" name="password" id="password"/> <br/> <button type="submit">Submit</button> </form> </body> </html>
package com.zhao.action; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.interceptor.ServletRequestAware; import com.opensymphony.xwork2.ActionSupport; public class JsonAction extends ActionSupport implements ServletRequestAware{ private static final long serialVersionUID = 1L; private Map<String, Object> info = new HashMap<String, Object>(); private HttpServletRequest request; @Override public String execute() throws Exception { String username=request.getParameter("username"); String password=request.getParameter("password"); System.out.println("username"+username); System.out.println("password"+password); info.put("username", username); info.put("password", password); return SUCCESS; } public Map<String, Object> getInfo() { return info; } public void setInfo(Map<String, Object> info) { this.info = info; } @Override public void setServletRequest(HttpServletRequest request) { this.request=request; } }
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <package name="json" namespace="/" extends="json-default"> <action name="json" class="com.zhao.action.JsonAction"> <result type="json"> <param name="root">info</param> </result> </action> </package> </struts>
完美运行,首先在页面进行验证,username password必须有值,然后控制了位数。通过了才会进行ajax的操作。