NutzCN Logo
问答 Ajax始终进error,回调函数接受的数据是Object,但是数据已经插入数据库
发布于 2804天前 作者 tangshiyu 1432 次浏览 复制 上一个帖子 下一个帖子
标签:
//jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>Register</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<script src='include/js/jquery-3.1.1.min.js'></script>
	<link rel="stylesheet" href="include/css/style.css">
<script type="text/javascript">
var base="<%=basePath%>";
$(document).ready(function () {
    $('#registerForm input').keydown(function (e) {
        if (e.keyCode == 13)
        {
        BasicCheck();
        }
    });
    $("#create").click(BasicCheck);  
});
 
function BasicCheck()//登录前,校验用户信息
{ 
	var uid=$("#uid").val();
   var name=$("#name").val();
   var password=$("#password").val();
   var email=$("#email").val();
   var department=$("#department").val();
   alert(uid+name+password);
   if(uid=="")
   {
   alert("考号不能为空!");
   return;   
   }
   if(password==""||password==undefined)
   {
    alert("密码不能为空!");
   return;
   }
   	 $.ajax({
      url : base+"user/addStudent",
      data :{"uid":uid,"name":name,"password":password,"email":email,"department":department},
      type:"POST",
      success : function (res) {
      	alert(res);
        if (res == "ok") {
        	alert(name+"恭喜注册成功!");
           window.location.href=base+"web/login.jsp";
        }else {alert(res);}
        return false;
      },
      error : function(res) {alert("系统错误!"+res);     }
   });
  }
</script>
  </head>
  <body>
	<div class="login-page">
		<div class="form">
			<form class="register-form"  method="POST" id="registerForm">
				<span style="font: 38px;font-weight: 700;line-height: 18px;">注册</span><br />
				<br />
				<!-- <input type="text" placeholder="Your ID" name="uid"/> -->
				<input type="text" placeholder="你的学号" name="uid" id="uid"/> 
				<input type="text" placeholder="你的名字" name="name" id="name"/> 
				<input	type="password" placeholder="密码" name="password" id="password"/> 
				<input
					type="text" placeholder="邮箱地址" name="email" id="email"/> 
					<input
					type="text" placeholder="系别" name="department" id="department"/>
					<input  type="submit" value="注册" id="create"/>
			</form>
				<p class="message">
					Already registered? <a href="${base}/web/login.jsp" target="_self">Sign In</a>
				</p>
			<p style="color:#4CAF50;font-size: 12px;">
				&copy;2017<a style="color:#4CAF50;text-decoration: none;"
					href="http://github.com/tangshiyu">Jarrem</a>
			</p>
		</div>
	</div>
  </body>
</html>

//java
package com.tang.module;
import javax.servlet.http.HttpSession;

import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.By;
import org.nutz.mvc.annotation.Fail;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.view.ServerRedirectView;

import com.tang.filter.LoginFilter;
import com.tang.pojo.User;
import com.tang.utils.Encrypt;
@IocBean
@At("/user")
@Ok("json")
@Fail("http:500")
@Filters({@By(type=LoginFilter.class)})
public class UserModule {

    @Inject
    protected Dao dao;

    @At
    public int count() {
        return dao.count(User.class);
    }
    @At
    @Filters
    public String login(@Param("uid")String uid, @Param("password")String password, HttpSession session) {
       String passwordCode = Encrypt.getCode(password, "tangshiyu");
    	User user = dao.fetch(User.class, Cnd.where("uid", "=", uid).and("password", "=", passwordCode));
        if (user == null) {
        	System.out.println("账户不存在或者密码错误!");
        	return "你的账户不存在!";
        } 
        		System.out.println(user.toString());
            	session.setAttribute("me", user);
              return user.getRole();
    }
    @At
    @Ok(">>:/")
    public void logout(HttpSession session) {
        session.invalidate();
    }
    @At
    @Filters
    public String addStudent(	@Param("uid")String uid,
					    		@Param("name")String name,
					    		@Param("password")String password,
					    		@Param("email")String email,
					    		@Param("department")String department
    		) {
    	User user=new User();
    	user.setUid(uid);
    	user.setName(name);
    	user.setPassword(password);
    	user.setEmail(email);
    	user.setDepartment(department);
    	user.setRole("0");
        String code = Encrypt.getCode(user.getPassword(), "tangshiyu");
        user.setPassword(code);
        System.out.println("beforeInsert="+user.toString());
        user = dao.insert(user);
        if(user==null){
        	return "error";
        }
        return "ok";
    }

    @At
    @Ok("jsp:/web/home")
    @Filters
   // @Ok("beetl:web/home.jsp")
    public Object update(@Param("..")User user,HttpSession session) {
    	System.out.println("Update=="+user.toString());
        NutMap re = new NutMap();
        System.out.println(user.toString());
        String msg = updateCheck(user, false);
        if (msg != null){
            return re.setv("ok", false).setv("msg", msg);
        }
        if("".equals(user.getPassword())) user.setPassword(null);
        if("".equals(user.getName())) user.setName(null);
        if("".equals(user.getEmail())) user.setEmail(null);
        if("".equals(user.getDepartment())) user.setDepartment(null);
        dao.updateIgnoreNull(user);// 真正更新的其实只有password和salt
        User u2 = dao.fetch(User.class, user.getUid());
        session.setAttribute("me", u2);
        return re.setv("ok", true);
    }
    protected String  updateCheck(User user, boolean create){
    	 String passwd = user.getPassword().trim();
    	 if("".equals(passwd))
    	 System.out.println("updateTest"+passwd+"******");
    	 if(passwd!=null&&!"".equals(passwd)){
         if (6 > passwd.length() || passwd.length() > 12) {
             return "密码长度错误";
         }}
         user.setPassword(passwd);
         if (create) {
             int count = dao.count(User.class, Cnd.where("name", "=", user.getName()));
             if (count != 0) {
                 return "用户名已经存在";
             }
         }
		return null; 
    }
    protected String checkUser(User user, boolean create) {
        if (user == null) {
            return "空对象";
        }
        if (create) {
            if (Strings.isBlank(user.getName()) || Strings.isBlank(user.getPassword()))
                return "用户名/密码不能为空";
        } else {
            if (Strings.isBlank(user.getPassword()))
                return "密码不能为空";
        }
        String passwd = user.getPassword().trim();
        if (6 > passwd.length() || passwd.length() > 12) {
            return "密码长度错误";
        }
        user.setPassword(passwd);
        if (create) {
            int count = dao.count(User.class, Cnd.where("name", "=", user.getName()));
            if (count != 0) {
                return "用户名已经存在";
            }
        } else {
//            if (user.getUid().length()< 1) {
//                return "用户Id非法";
//            }
        }
        if (user.getName() != null)
            user.setName(user.getName().trim());
        return null;
    }
}
17 回复

一般来说是json格式不合法. 改成

@Ok("json:full")

另外, 一般不是直接用字符串作为返回值的, ajax的入口方法一般返回个map, 然后经由nutz转为json字符串,传给前端

另外, error有多个参数,可以全部打印一下,看看具体报的原因

http://api.jquery.com/jquery.ajax/

error
Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )

多谢,我再试试

XMLHttpRequest status = 0
XMLHttpRequest status = 0
返回的参数是
if(user==null){
return "error";
}
但是我数据都插入到数据库了,都可以打印到控制台了
类前面已经加了@Ok("json:full")
已经调试了一天了[Cry][Cry]

        user = dao.insert(user);
        if(user==null){ // 这里不会是null吧? 灵异了?? 另外,这个判断可以去掉的. 要是插入失败,是抛异常的,而非返回null.
        	return "error";
        }
        return "ok";

addStudent 为什么传递uid,uid不是自增长主键么?

@Wizzercn 我这里设置的是注册输入,这不是根本问题,我觉得灵异了为什么在前端拿不到数据@wendal,还是没有解决,我把dateType改为Text也没有用,XMLHttpRequest status = 0XMLHttpRequest status = 0,去掉succee函数status才=200

你先确定后台的方法走到哪里了,是否已经return ok了

恩恩,已经返回了

能不能辛苦你一下,帮我远程解决一下?QQ2573989549@wendal

加一下QQ群吧: 68428921

"去掉succee函数status才=200", 难道是你的success方法抛异常了?

话说, error方法你现在写成啥样子了,贴出来, 整个ajax调用

<script type="text/javascript">
var base="<%=basePath%>";
$(document).ready(function () {
    $('#registerForm input').keydown(function (e) {
        if (e.keyCode == 13)
        {
        BasicCheck();
        }
    });
    $("#create").click(BasicCheck);  
});
 
function BasicCheck()//登录前,校验用户信息
{ 
	var uid=$("#uid").val();
   var name=$("#name").val();
   var password=$("#password").val();
   var email=$("#email").val();
   var department=$("#department").val();
   alert(uid+name+password);
   if(uid=="")
   {
   alert("考号不能为空!");
   return;   
   }
   if(password==""||password==undefined)
   {
    alert("密码不能为空!");
   return;
   }
   	 $.ajax({
      url : base+"user/addStudent",
      data :{"uid":uid,"name":name,"password":password,"email":email,"department":department},
      type:"POST",
      success : function (res) {
        if (res == "ok") {
        	alert(name+"恭喜注册成功!");
           window.location.href=base+"web/login.jsp";
        }else {alert(res);}
      },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
									 alert(
									 "XMLHttpRequest.status"+XMLHttpRequest.status+"----"+
									 "XMLHttpRequest status ="+XMLHttpRequest.readyState+"----"+
									 "textStatus="+textStatus);
  			 	}
   });
  }
</script>

我是群里的成员了,请问你的网名是什么?@wendal

这error方法写得真揪心啊. 怎么可以用XMLHttpRequest做变量名...

要看的是 errorThrown

error: function(xhr, textStatus, errorThrown) {
         if (console)
             console.log(errorThrown);
         alert(errorThrown);
}

控制台没有报错,还是进入error,我已经把截图发到你的QQ上了@wendal

添加回复
请先登陆
回到顶部