【问题标题】:How to render a template after a post request with Ajax in Flask [duplicate]如何在 Flask 中使用 Ajax 发布请求后呈现模板 [重复]
【发布时间】:2019-02-06 07:39:55
【问题描述】:

我想在 jQuery ajax 发布请求之后呈现一个新模板。当我使用 jquery/ajax 发出请求时,我该怎么做?

这是发送 post 请求的初始路由。

@app.route("/data")
def data():
if request.method=='GET':
    cursor.execute("SELECT * from data")
    data = cursor.fetchall()
    cursor.execute("DESCRIBE data")
    headers = cursor.fetchall()
    return render_template("data.html", data=data, headers=headers)

这是发送请求的 data.html 中的 jQuery

...
<script>
  $(document).ready(function(){
    $('.row').each(function(){
      $(this).click(function(){
        let rowId = $(this).attr('id');
        var data_send = {'id' : rowId};
        $.ajax({
          type:'POST',
          url: '{{ url_for('row') }}',
          data : JSON.stringify(data_send),
          dataType: "json"
        })
      })
    })
  });
</script>

这是接收post请求的方法:

@app.route('/row', methods=['POST'])
def row():
    recieved_data = request.get_data().decode('utf8')
    target_id = json.loads(recieved_data)['id']
    cursor.execute("DESCRIBE data")
    headers = cursor.fetchall()
    cursor.execute("SELECT * from data")
    data = cursor.fetchall()[int(target_id)]
    return render_template("row.html",data = data, headers=headers)

即使服务器接收到 post 请求没有问题,浏览器也不会重定向到 row.html。我不想发回重定向 URL 和 JSON,而是实际呈现模板。

【问题讨论】:

    标签: jquery ajax flask


    【解决方案1】:

    您可以使用 html 呈现的模板从 ajax 响应中设置 html attribute,例如 $('#some_id').html(response)。详情见以下示例:

    ...
    <script>
      $(document).ready(function(){
        $('.row').each(function(){
          $(this).click(function(){
            let rowId = $(this).attr('id');
            var data_send = {'id' : rowId};
            $.ajax({
              type:'POST',
              url: '{{ url_for('row') }}',
              data : JSON.stringify(data_send),
              dataType: "json",
              success: function(response) {
                $(this).html(response);
              }
            })
          })
        })
      });
    </script>
    

    【讨论】:

      【解决方案2】:

      视图函数不允许GET请求,所以浏览器无法打开row.html。

      试试

      @app.route('/row', methods=['GET', 'POST'])
      def row():
          data = None
          headers = None
          if request.methods == 'POST':
              recieved_data = request.get_data().decode('utf8')
              target_id = json.loads(recieved_data)['id']
              cursor.execute("DESCRIBE data")
              headers = cursor.fetchall()
              cursor.execute("SELECT * from data")
              data = cursor.fetchall()[int(target_id)]
          return render_template("row.html",data = data, headers=headers)
      

      【讨论】:

        猜你喜欢
        • 2020-08-31
        • 2018-07-04
        • 1970-01-01
        • 2021-09-26
        • 2020-08-04
        • 2021-12-17
        • 2018-03-02
        • 2012-04-03
        • 2019-11-03
        相关资源
        最近更新 更多