func (u *UserController) DoAdd() {
username := u.GetString("username")
password := u.GetString("password")
age,_ := u.GetInt("age")
gender,_ := u.GetInt("gender")
phone := u.GetString("phone")
addr := u.GetString("addr")
is_active,_ := u.GetInt("is_active")
new_password := utils.GetMd5Str(password)
phone_int64,_ := strconv.ParseInt(phone,10,64)
o := orm.NewOrm()
user_data := auth.User{UserName:username,Password:new_password,Age:age,Gender:gender,Phone:phone_int64,Addr:addr,IsActive:is_active}
_,err := o.Insert(&user_data)
message_map := map[string]interface{}{}
if err != nil { //说明插入数据有问题
ret1 := fmt.Sprintf("插入数据信息:username:%s|md5_password:%s|age:%d|gender:%d|phone:%s|" +
"addr:%s;is_active:%d",username,new_password,age,gender,phone,addr,is_active)
ret := fmt.Sprintf("添加数据出错,错误信息:%v",err)
logs.Error(ret1)
logs.Error(ret)
message_map["code"] = 10001
message_map["msg"] = "添加数据出错,请重新添加"
u.Data["json"] = message_map
}else {
ret1 := fmt.Sprintf("插入数据成功,数据信息:username:%s|md5_password:%s|age:%d|gender:%d|phone:%s|" +
"addr:%s;is_active:%d",username,new_password,age,gender,phone,addr,is_active)
logs.Info(ret1)
message_map["code"] = 200
message_map["msg"] = "添加成功"
u.Data["json"] = message_map
}
u.ServeJSON()
}
前端
form.on('submit(add)', function (data) {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var age = document.getElementById("age").value;
var gender = $("input[name='gender']:checked").val();
var phone = document.getElementById("phone").value;
var addr = document.getElementById("addr").value;
var is_active = $("input[name='is_active']:checked").val();
if (password.length < 6){
alert("密码长度不能小于6个字符");
return
}
$.ajax({
url:"{{urlfor "UserController.DoAdd"}}",
type:"POST",
data:{
"username":username,
"password":password,
"age":age,
"gender":gender,
"phone":phone,
"addr":addr,
"is_active":is_active
},
success:function (data) {
var code = data.code;
if(code == 200){
alert(data.msg);
setTimeout(reload_list,2000); // 2s
}else {
alert(data.msg)
}
},
fail:function (data) {
alert(data)
}
});