如何将Json数据从javaScript发送到Flask [英] How can I send Json Data from javaScript to Flask

查看:60
本文介绍了如何将Json数据从javaScript发送到Flask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作Dyanmic表单生成器.构建过程结束后,我试图通过脚本将所有表单数据放入JsonObject中,并将其传递给flask视图,以便向用户显示它们.但是我无法正确设置.这是调用javascript的按钮

I am trying to make a Dyanmic Form Builder. After the building process I am trying to put all form data in a JsonObject by a script and pass it to a flask view so I can show them to the user. But I couldn't set it up correctly. Here is the button calls the javascript

<form action="/preview" method="post" role="form">
<button class="btn btn-primary" name = "submit" id = "submit">submit</button>
</form>

这是我进行ajax调用的脚本.

And here is the script that I make the ajax call.

<script>
     $(document).ready( function() {
        $('#submit').click(function() {
           var formdata = serialize();
           $.ajax({
                 type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(formdata),
                dataType: 'json',
                url: 'http://192.168.58.206:5000/index',
                success: function (e) {
                    console.log(e);
                },
                error: function(error) {
                console.log(error);
                }
                });
            });
        });
</script>

这是我尝试在烧瓶python中进行渲染的方法.

And here is how I try to render in flask python.

@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        asd = request.json
        session['formdata'] = asd
        if 'formdata' in session:
            return json.dumps({'success': True}), 200, {'ContentType': 'application/json'}
    return render_template("index.html")

@app.route('/preview', methods=['GET', 'POST'])
def preview():
    if 'formdata' in session:

        renderedform = formbuilder(json.dumps(session['formdata']))
        renderedform = renderedform.renderform()
        session.pop('formdata')
        return render_template("asd.html",renderform = renderedform)
    return "Error"

我的renderdorm()方法将json对象作为参数,并为表单创建相应的html块.

My renderdorm() method takes the json object as parameter and creates the corresponding html blocks for the form.

但是当我以这种方式运行它时,有时按钮操作会将我定向到/preview路由,然后脚本开始运行并创建json对象.因此,这将导致会话的formdata为None.

But when I run it this way,sometimes button action directs me to the /preview route before the scripts runs and creates the json object. So this causes formdata of the session to be None.

任何想法如何传递json对象以在预览中呈现?

Any ideas how can I pass that json object to render in preview ?

推荐答案

您需要删除表单上的操作字段,因为当用户单击按钮操作时,可能未设置会话

you need to remove the action field on your form because when the user clicks the button action is called session may not be set

<form method="post" role="form">
<button class="btn btn-primary" name = "submit" id = "submit">submit</button>
</form>

然后在ajax上成功设置为窗口位置

then on ajax you need to set to window location on success

  <script>
         $(document).ready( function() {
        $('#submit').click(function() {
           var formdata = serialize();
           $.ajax({
                 type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(formdata),
                dataType: 'json',
                url: 'http://192.168.57.223:5000/createform',
                success: function (e) {
                    console.log(e);
                    window.location = "http://192.168.57.223:5000/preview";
                },
                error: function(error) {
                console.log(error);
            }
            });
        });
  });
    </script>

然后您的python脚本应如下所示,您需要说出您的值,而ajax会设置所需的窗口位置

then your python script should look like this you need to say that you took the value and ajax would set the desired window location

@app.route('/index', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        asd = request.json
        print(asd)
        session['formdata'] = asd
        if 'formdata' in session:
            return json.dumps({'success': True}), 200, {'ContentType': 'application/json'}
    return render_template("createform.html")

这篇关于如何将Json数据从javaScript发送到Flask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆