ajaxSubmit返回JSON格式
开发时遇到根据不同情况返回错误提示信息的需求,用到了ajax中返回json格式数据的。
前台请求代码:
<script type="text/javascript">
function login() {
$.ajax({
//几个参数需要注意一下
type: "POST",//方法类型
dataType: "json",//预期服务器返回的数据类型
url: "login.action" ,//url
data: $(‘#form1‘).serialize(),
success: function (data) {
console.log(data);//打印服务端返回的数据(调试用)
if (ata.code ==200
) {
alert("登录成功!");
}else{
alert("登陆失败!"+data.Msg);
}
;
}
});
}
</script>
后台接收代码:
//验证登录
@RequestMapping(value="/login",method=RequestMethod.POST,produces = "text/html;charset=UTF-8")
@ResponseBody
public void login(User user,HttpServletResponse response) throws IOException{
JSONObject json=new JSONObject();
if (user.getUpassword().equals("123")) {
json.put("code", 200);
json.put("Msg", "验证成功!");
}else {
json.put("code", 400);
json.put("Msg", "密码错误");
}
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");//防止乱码
response.getWriter().print(json.toJSONString());
}
后台controller中的方法使用时是返回的JSONObject类型,未使用注解,修改为
方法名: public JSONObjectlogin(User user,HttpServletResponse response) 返回值:return json
注:用到JSONObject()方法需引入6个jar包,不然会报java.lang.NoClassDefFoundError错误。
<span>json<span>-<span>lib<span>-<span>2.4<span>-<span>jdk15<span>.<span>jar</span></span></span></span></span></span></span></span></span>
<span>commons<span>-<span>beanutils<span>-<span>1.8<span>.<span>0.jar</span></span></span></span></span></span></span>
<span>commons<span>-<span>logging<span>-<span>1.1<span>.<span>1.jar</span></span></span></span></span></span></span>
<span>commons<span>-<span>collections<span>-<span>3.2<span>.<span>1.jar</span></span></span></span></span></span></span>
<span>commons<span>-<span>lang<span>-<span>2.5<span>.<span>jar</span></span></span></span></span></span></span>
<span>ezmorph<span>-<span>1.0<span>.<span>6.jar</span></span></span></span></span>
————————————————
版权声明:本文为CSDN博主「程序员xiaoQ」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_42304232/java/article/details/89713452