ajax .show() 在注册时没有显示隐藏的 div?



我试图在新用户注册时(通过表单(显示成功警报或错误警报div并返回json消息。我可以在控制台中看到json输出(即消息填充在控制台中(,但我看不到div和对象,因为文本显示在html页面上。

以下是我所拥有的:

Html:

<script src="../static/js/jquery-3.3.1.min.js"></script>
<script src="../static/js/signUp.js"></script>
<div id="successAlert" class="alert alert-success" role="alert" style="display:none;"></div>
<div id="errorAlert" class="alert alert-danger" role="alert" style="display:none;" ></div>

注册js:

$(document).ready(function(){
$("#btnSignUp").click(function(){
$.ajax({
type: "POST",
url: "/signUp",
data: $("form").serialize(),
success: function(response){
$("#successAlert").html("response").show();
},
error: function(error){
$("#errorAlert").html("error").show();
}
});
});
});

注册py:

@app.route("/signUp",methods=["POST", "GET"])
def signUp():
try:
_name = request.form["inputName"]
_email = request.form["inputEmail"]
_password = request.form["inputPassword"]
# validate the received values
if _name and _email and _password:
conn = mysql.connect()
cursor = conn.cursor()
_hashed_password = generate_password_hash(_password)
cursor.callproc("sp_createUser",(_name,_email,_hashed_password))
data = cursor.fetchall()
if len(data) is 0:
conn.commit()
return jsonify({"message":"User created successfully !"})
else:
return jsonify({"error":str(data[0])})
except Exception as e:
return jsonify({"error":str(e)})
finally:
cursor.close()
conn.close()

提前谢谢!

不要用.html()替换#successAlert中的所有内容,而是使用.append()并将dataType:'json'添加到ajax:

$.ajax({
type: "POST",
url: "/signUp",
data: $("form").serialize(),
dataType:'json', // <------add this to parse the response as json
success: function(response){
$("#successAlert").append(response.message).show();// put message then show.
},
error: function(error){
$("#errorAlert").append(error.error).show();// put error then show.
}
});

$(document).ready(function(){
$("#btnSignUp").click(function(){
$.ajax({
type: "POST",
url: "/signUp",
data: $("form").serialize(),
success: function(response){
$("#successAlert").html("response").show();
},
error: function(error){
$("#errorAlert").html("error").show();
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="successAlert" class="alert alert-success" role="alert" style="display:none;"></div>
<div id="errorAlert" class="alert alert-danger" role="alert" style="display:none;" ></div>
<input type="submit" id="btnSignUp">

错误div正在中工作

不确定其中哪一个是修复方法,但我认为我通过在html页面上的js脚本导入中添加type="text/javascript"来解决了问题。此外,当在本地运行webapp时,除非我更改文件名,否则我的css和js文件不会更新(这很奇怪(。我将为这个问题提出一个新的问题。

HTML已调整为:

<script type="text/javascript" src="../static/js/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="../static/js/signUp.js"></script>

谢谢你的帮助!

最新更新