render_template无法呈现POST请求中指定的模板

时间:2019-06-20 21:38:23

标签: javascript ajax flask

在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。而是,它停留在同一页面上。我在这里做错了什么?如果需要,我可以提供更多详细信息。

1 个答案:

答案 0 :(得分: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)
       }
     };
  }
}

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

请找到this example