首页 > 解决方案 > 使用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"}

控制台也不记录任何内容

标签: ajaxflask

解决方案


试试这个:

$.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 错误(错误请求)。见这里


推荐阅读