在Flask App中添加Ajax之后,文本未使用render_template更改

时间:2018-07-14 08:13:11

标签: javascript python ajax flask flask-wtforms

我创建了一个简单的AJAX,无需刷新页面即可将数据发送到烧瓶路径,数据似乎到达了该路径,但是在render_template之后它并没有更改文本。

MyForm是一个简单的下拉列表。我试图在提交表单或单击按钮后显示当前选择的文本,而不使用AJAX刷新页面。

run.py

from flask import Flask, redirect, render_template, request, jsonify
from forms.myform import MyForm
import json
import plotly
import pandas as pd, numpy as np

server = Flask(__name__)

server.config.update(dict(
    SECRET_KEY="powerfulsecretkey",
    WTF_CSRF_SECRET_KEY="a csrf secret key"
))

@server.route("/", methods=["POST", "GET"])
def index():
    form = MyForm()
    choice = request.form.get('options')
    if form.validate_on_submit():
        choice = request.form.get('options')

    print(choice)

    return render_template("index.html", form=form, choice=choice)


if __name__ == "__main__":
    server.run()

表格

from flask_wtf import FlaskForm
import wtforms


class MyForm(FlaskForm):
    options = wtforms.SelectField(label="State", choices=[("SF", "SF"),
                                                          ("LA", "LA")])

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form method="POST" id="fm" action="/">
    {{ form.csrf_token }}
    <div>{{ form.options}}</div>
</form>
<button type="submit" form="fm" value="Submit">Submit</button>
<div>{{ choice }}</div>
</body>

<footer>
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script>
          $('form').on('submit', function(e){
                $.ajax({
                    type: 'POST',
                    data:$('form').serialize(),
                    url: '/',
                    success: function(data) {
                        console.log(data);
                    },
                    error: function(jqXHR) {
                        alert("error: " + jqXHR.status);
                        console.log(jqXHR);
                    }
                });
                e.preventDefault();
             });

            // Inject our CSRF token into our AJAX request.
            $.ajaxSetup({
            beforeSend: function(xhr, settings) {
                if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader("X-CSRFToken", "{{ form.csrf_token._value() }}")
                }
            }
        })

    </script>
</footer>


</html>

浏览器 enter image description here

1 个答案:

答案 0 :(得分:1)

因为您是ajax提交的表单,页面未重新渲染,Jinja2是要生效的渲染​​