【问题标题】:render_template not rendering the template specified on a POST request [duplicate]render_template 未呈现 POST 请求中指定的模板 [重复]
【发布时间】:2019-11-03 18:15:15
【问题描述】:

在 index.html 中,我得到了一个存储在 localStorage 中的值:

    <script>
        function checkChannel() {
                        if (localStorage.getItem('channel')) {
                            const channel = localStorage.getItem('channel');
                            const request = new XMLHttpRequest();
                            request.open('POST', '/convert');
                            // Add data to send with request
                            const data = new FormData();
                            data.append('channel', channel);

                            // Send request
                            request.send(data);
                         }
        }
    </script>
</head>

<body onload="checkChannel()">
    .
    .
    .

这很好用。它被路由到 application.py 中的以下代码。调试器点击了下面 convert() 的第一行,所以我知道它已经到了。

@app.route("/convert", methods=["POST"])
def convert():
    channel = request.form.get("channel")
    channel_messages = channels_dict[channel]
    return render_template("channel.html", channel=channel, channel_messages=channel_messages)

但是,channel.html 没有被渲染。相反,它保持在同一页面上。我在这里做错了什么?如果需要,我可以提供更多详细信息。

【问题讨论】:

    标签: javascript ajax flask


    【解决方案1】:

    您需要定义一个request.onload() 函数。收到响应后将调用此函数。所以你的 JS 代码将类似于:

    function checkChannel() {
      if (localStorage.getItem('channel')) {
          const channel = localStorage.getItem('channel');
          const request = new XMLHttpRequest();
          request.open('POST', '/convert');
          // Add data to send with request
          const data = new FormData();
          data.append('channel', channel);
    
         // Send request
         request.send(data);
    
         // 4. This will be called after the response is received
         request.onload = function() {
           if (request.status != 200) {
              // analyze HTTP status of the response
              alert(`Error ${request.status}: ${request.statusText}`);
              // e.g. 404: Not Found
           } else { // show the result
              $('body').html(request.response)
           }
         };
      }
    }
    

    请注意,您可以根据channel.html 文件内容将$('body').html('some content') 替换为$('div').html('some content')$('#some-id').html('some content')

    请找this example

    【讨论】:

    • 可以,但是新页面上的DOMContentLoaded 事件没有触发。
    • 尝试使用 $('body') 而不是 $(body)。请找到我的编辑。
    • 其实我是这样操作的:document.body.innerHTML = request.response
    • 是的,替换正文内容有很多解决方案。
    猜你喜欢
    • 2022-01-26
    • 2020-08-04
    • 1970-01-01
    • 2020-10-27
    • 2017-09-14
    • 2019-01-06
    • 2022-01-25
    • 2019-02-06
    • 1970-01-01
    相关资源
    最近更新 更多