$(function() {
$("#loginBtn").click(function() {
var username = $("#userName").val();
var id_card = $("#id_card").val();
$.ajax({
type:"POST",
url:"login.do",
data:{"userName" : username,"id_card" : id_card},
dataType:"json",
success:function(data){
if(data=="success"){
window.location.href = "index.jsp";
}else{
window.location.href = "login.jsp";
}
}
});
});
});
后台控制层
@RequestMapping(value="/login.do")
@ResponseBody
public String loginAccount(String userName,String id_card,HttpServletRequest request,HttpServletResponse response) throws IOException{
String login = classificationService.login(userName, id_card);
String re;
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
if(login!=null){
re="success";
System.out.println(re);
}else{
re="login";
System.out.println(re);
}
return re;
}
首先你要搞清楚是哪里的错误,是前端还是后端你可以走debug,然后在ajax里面接收值,来逐步排查
后台这样写
try {
PrintWriter out = reponse.getWriter();
out.print("success");
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
在浏览器中中给js打个断点,看看接收到的data是什么值
我感觉是前台url前要加上项目路径
method=post
href 要加项目路径吧,应该是路径错误把
楼主再做什么呢? 其他代码不看,只看第一张图片就有问题
!!!jsp文件是不可以直接访问的!!!
你要访问indx.jsp或login.jsp,在location.href的位置就写这两个jsp的请求路径,而不是直接写jsp!!!
首先你看你的请求走到哪了?chrome打开也,F12, network,看看你的请求报什么错?
在你该类后台最上方的类上有个@RequestMapping("/thirdConfig"),是标明该类的地址的,你的ajax的url路径只是指向了该类中的方法,没有指向该类,所以你没访问到后台,当然也没法跳转了,
也不排除其他问题,希望能对你起到帮助
我对你的代码做了一下模拟测试,,,你这个错误原因是,后台传过来的data不是json的,,,,
你ajax设置了 type:"json",,,交互的数据必须是标准的json
我对你的代码做了如下调整,,测试通过,,完美运行:
// 后台控制层
@RequestMapping(value="/login.do" ,method = RequestMethod.POST)
@ResponseBody
public List<String> loginAccount(String userName,String id_card, HttpServletRequest request, HttpServletResponse response) throws IOException {
// String login = classificationService.login(userName, id_card);
List<String> re = new ArrayList<>();
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
if(1==1){
re.add("success");
System.out.println(re);
}else{
re.add("login");
System.out.println(re);
}
return re;
}
最后,,String貌似不会被封装成json,而是直接输出,,需要用集合,当然用map也行,,
我这只是个参考,,个性化你可以自己丰富。。
纯手码,,如果解决你的问题了,,给个采纳呗。。 ^.^