我正在尝试显示成功警报或错误警报div,并在新用户注册时(通过表单)返回json消息。我可以在控制台中看到json输出(即,在控制台中填充的消息),但在html页面上看不到div或文本对象。
以下是我所拥有的:
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()
提前谢谢!
答案 0 :(得分:0)
使用#successAlert
并将.html()
添加到ajax中,而不是将.append()
中的所有内容替换为dataType:'json'
:
$.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.
}
});
答案 1 :(得分:0)
$(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工作正常
答案 2 :(得分:0)
不确定其中的哪个是修复程序,但是我想我通过在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>
谢谢您的帮助!