jQuery的Ajax与Spring MVC对接注意事项(2)

@RequestMapping(value = "/checkLogin",method = RequestMethod.POST) public @ResponseBody Object userLogin(TUserLoginVo tUserLoginVo, HttpServletRequest request,HttpServletResponse response){ HttpSession session=request.getSession(); String code= (String) session.getAttribute("code"); System.out.println("---"+session.getAttribute("code")); if(code.equals(tUserLoginVo.getCheckcode())){ TUser tUser=staffService.finUser(tUserLoginVo.getUsername(),tUserLoginVo.getPassword()); if(tUser!=null){ System.out.println("---"+tUser.getUsername()); return "{\"LoginOK\":\"LoginOK\"}"; } } return "{\"LoginError\":\"LoginError\"}"; } 

问题解决了,前台执行了success的方法!

当然,上面的方法也不好,那怎么办,我们需要的是json,但又无法转得了。

可以这一,给一个通用方法:

package com.liyong.bos.utils; import java.io.Serializable; import java.util.List; public class JsonResult<T, K> implements Serializable { private boolean result; private String msg; private List<T> dataList; private K data; private T dataObje; public K getData() { return data; } public void setData(K data) { this.data = data; } public List<T> getDataList() { return dataList; } public void setDataList(List<T> dataList) { this.dataList = dataList; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public boolean isResult() { return result; } public void setResult(boolean result) { this.result = result; } public T getDataObje() { return dataObje; } public void setDataObje(T dataObje) { this.dataObje = dataObje; } }

把我们需要的数据封装到jsonResult对象中即可,然后返回值是JsonResult就行。具体功能请看代码。

然后前台就可以用这种方式接收:

<script type="text/javascript"> $(function() { $('#submitLogin').click(function() { $.ajax({ type:"POST", url:"/user/checkLogin", dataType: "json", data: $("#loginform").serialize(), success:function(data,status){ if(data.msg=="success"){ location.href="/pages/test.html"; }else if(data.msg=="error"){ location.href="/pages/LoginPage.html"; } }, error:function () { alert("失败"); } }); }); }); </script>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/ada8c9e27ab2f053534c96ef79501983.html