如何解决收到Ajax内容烧瓶,python,javascript后,render_template不执行任何操作
当满足条件时,我正在使用ajax将数据传递给python函数:
if (lesson.length === 0) {
$.ajax(
{
type:'POST',contentType:'application/json',dataType:'json',url:'http://127.0.0.1:5000/result?value=' + errors,success:function(response){ document.write(response); }
}
);
}
我知道信息已经正确接收,因为我可以通过打印在终端上看到它:
127.0.0.1 - - [19/Aug/2020 11:59:46] "GET /static/flexjava.js HTTP/1.1" 200 -
0
127.0.0.1 - - [19/Aug/2020 11:59:48] "POST /result?value=0 HTTP/1.1" 200 -
但是python在print()函数之后什么也不做。呈现或重定向均无效,即使传递了信息,浏览器仍保持原样:
@app.route("/result",methods=["GET","POST"])
def result():
content = request.args.get('value')
if "username" not in session or session["username"] == "guest":
return redirect("/login")
if request.method == "GET":
return redirect("/")
else:
print(content)
return render_template("finished.html")
解决方法
您没有正确使用ajax。您想收到一个json
的回复,而不是完整的网页。
尝试:
$.ajax(
{
type:'POST',contentType:'application/json',dataType:'json',url:'http://127.0.0.1:5000/result?value=' + errors,success:function(response){
console.log(response);
document.write(response); # not a good idea
# I would use something like:
# document.getElementById("myDiv").innerText = response.content;
}
}
);
然后:
from flask import jsonify
@app.route("/result",methods=["GET","POST"])
def result():
content = request.args.get('value')
...
else:
print(content)
return jsonify(
{
"content": content
}
)
此功能实际上没有任何作用,因为调用模板中已经包含errors
。如果您尝试转到finished
,则可以在ajax success
回调中进行此操作:
success:function(response){
console.log(response);
window.location.replace(window.location.href + "finished");
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。