1.页面
$.ajax({
type: "POST",
url: ******,
data: $('#loginForm').serialize(),
//json格式的字符串,此处传的数据是form表单中的数据,经过序列化可传递(name="name"&password="password")。也可以自己写json格式的字符串。
dataType: 'json',//设置需要返回的数据类型
success: function(data) {
else{}
},
error:function(){
alert("系统异常,请稍后重试!");
}
或者
$.post(url,str,function(data){
},"json");
//url对应后台地址,str代表要传到后台的数据,data表示在后台返回的数据,json代表返回的数据类型。
3.后台代码
public String execute() {
HttpServletResponse response=ServletActionContext.getResponse();
response.setContentType("application/json" + ";charset=UTF-8");
String name= request.getParameter("name");
String password= request.getParameter("password");
//根据前台传来的用户名和密码,在数据中查询是否存在。若存在返回数据loginsuccess,不成功返回false。
if(用户存在){
data="loginsuccess";
}else{
data="false";
}
try {
response.getWriter().write(data);
response.getWriter().flush();
response.getWriter().close();
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}
4.配置struts2.xml
<struts>
<package name="**" extends="json-default" >
<action name="**Action" class="com.****Action" method="execute">
<result type="json"></result>
</action>
</package>
</struts>
注意,json的命名空间跟其他的不一样。