我们接下来要实现的就是密码的修改
修改密码这个部分并不是很难,我们先放上前端的代码
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>用户中心</title> 6 <link rel="stylesheet" type="text/css" href="../../static/news/css/reset.css"> 7 <link rel="stylesheet" type="text/css" href="../../static/news/css/main.css"> 8 <script type="text/javascript" src="../../static/news/js/jquery-1.12.4.min.js"></script> 9 <script type="text/javascript" src="../../static/news/js/user_pass_info.js"></script> 10 </head> 11 <body class="inframe_body"> 12 <form class="pass_info"> 13 <h3>密码修改</h3> 14 <div class="form-group"> 15 <label>当前密码:</label> 16 <input type="password" name="old_password" class="input_txt"> 17 </div> 18 <div class="form-group"> 19 <label>新密码:</label> 20 <input type="password" name="new_password" class="input_txt"> 21 </div> 22 <div class="form-group"> 23 <label>确认密码:</label> 24 <input type="password" name="new_password2" class="input_txt"> 25 </div> 26 <div class="error_tip">提示信息</div> 27 <div class="form-group"> 28 <input type="submit" value="保 存" class="input_sub"> 29 </div> 30 </form> 31 </body> 32 </html>
然后是js得代码
1 function getCookie(name) { 2 var r = document.cookie.match("\b" + name + "=([^;]*)\b"); 3 return r ? r[1] : undefined; 4 } 5 6 7 $(function () { 8 $(".pass_info").submit(function (e) { 9 e.preventDefault(); 10 11 // TODO 修改密码 12 //定义一个名为params得空字典用来接收html得新旧密码 13 var params = {}; 14 $(this).serializeArray().map(function (x) { 15 //通过key:value形式将html中得参数放进去,这里是将html中所有参数都接收 16 params[x.name] = x.value; 17 }); 18 // 取到两次密码进行判断 19 var new_password = params["new_password"]; 20 var new_password2 = params["new_password2"]; 21 22 if (new_password != new_password2) { 23 alert('两次密码输入不一致') 24 return 25 } 26 27 $.ajax({ 28 url: "/user/pass_info", 29 type: "post", 30 contentType: "application/json", 31 headers: { 32 "X-CSRFToken": getCookie("csrf_token") 33 }, 34 data: JSON.stringify(params), 35 success: function (resp) { 36 if (resp.errno == "0") { 37 // 修改成功 38 alert("修改成功"); 39 window.location.reload(); 40 }else { 41 alert(resp.errmsg) 42 } 43 } 44 }); 45 }); 46 });
一样的修改个人中心主页html中修改密码部分页面的调用
最后就是后端的代码
1 @user_blue.route("/pass_info",methods = ["POST","GET"]) 2 @user_login_data 3 def pass_info(): 4 user = g.user 5 # 接收用户信息同时判断是否登录 6 if not user: 7 return redirect(url_for('index.index')) 8 # 当需要提交数据的时候 9 if request.method == "POST": 10 #接收参数 11 old_password = request.json.get("old_password") 12 new_password = request.json.get("new_password") 13 #校验前端传来的和数据库中进行对比 14 if not user.check_password(old_password): 15 return jsonify(errno=RET.PWDERR, errmsg="旧密码不正确") 16 user.password = new_password 17 try: 18 #提交 19 db.session.commit() 20 except Exception as e: 21 current_app.logger.error(e) 22 return jsonify(errno=RET.DATAERR, errmsg="错误") 23 24 return jsonify(errno=RET.OK, errmsg="密码修改成功") 25 26 context = { 27 "user": user.to_dict() if user else None 28 } 29 return render_template("news/user_pass_info.html",context=context)