ajax - 使用ajax发布json后无法更改HTML内容
问题描述
我正在使用烧瓶写一个小网站使用邮递员发送帖子请求
应用程序.py
@app.route('/index', methods=['GET', 'POST'])
def index():
if session["logged_in"]:
return render_template('index.html')
else:
return redirect(url_for('login'))
@app.route('/get_msg', methods = ['POST'])
def get_msg():
time_toshow = request.get_json(force = True)
return time_toshow
index.html(主要部分)
<script>
$(document).ready(function(){
$.ajax({
url: "{{url_for('get_msg')}}",
type: 'post',
dataType: 'json',
contentType: 'application/json',
success: function (data) {
$('#shown').html(data);
console.log(data);
},
});
})
</script>
</head>
<body>
<h1 id='shown' class='blackshadow' style="font-size: 80px">Good</h1>
</body>
通过 Postman 发送发布请求后,该网页永远不会更新,我发送给的发布请求http://127.0.0.1:5000/get_msg
是:
{"AbnormalTime": "5000"}
控制台也不记录任何内容
解决方案
试试这个:
$.ajax({
url: "{{url_for('get_msg')}}",
type: 'post',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(time_toshow),
success: function (data) {
$('#shown').html(JSON.stringify(data));
console.log(data);
},
});
注意 JSON.stringify(),无论是在成功函数中还是在传递数据时。
如果您不使用 JSON.stringify(),您的 JSON 将转换为 AbnormalTime=5000 而不是 {"AbnormalTime": "5000"},因此服务器返回 400 错误(错误请求)。见这里。
推荐阅读
- macos - 如何让iTerm2出现在当前空间?
- html - ul CSS 中的间距
- regex - 使用 Perl 的多个匹配表达式
- sql-server - 如何在 MacOS 上将 .xlsx 文件导入 SQL Server 数据库?
- python - Python:一次提交多个命令
- php - SQL bigint 数据类型被 gettype() 视为字符串;功能。为什么?
- javascript - 在没有 PHP 的网站之间传递 Javascript 变量的最佳/最安全的方法?
- php - 会话管理系统
- python - 从 numpy 中的 1d 向量映射 2d 延迟向量
- math - 如何在 spoj 上解决 ALICESIE。它的答案如何有共同的模式