如何从ajax POST表单提交使用Flask的render_template [英] How to use Flask's render_template from an ajax POST form submit

查看:875
本文介绍了如何从ajax POST表单提交使用Flask的render_template的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望对此类似问题的答案. :

I am hoping to get an answer to this similar question:

我有一个jQuery表单,可将​​JSON数据发送到Flask提供的某个URL:

I have a jQuery form that sends JSON data to a certain URL that is served by Flask:

    <div id="form">      
      <form id="send">        
        <input type="submit" value="Continue" >
      </form>
    </div>



jQuery(document).on('ready', function() {
        jQuery('form#send').bind('submit', function(event){
        event.preventDefault();

        var form = this;
        json = geojson.write(vectors.features);

        $.ajax({
            type: "POST",
            contentType: 'application/json',
            url: $SCRIPT_ROOT + "/create",
            dataType: "json",
            success: function(){},
            data: json

        });
    });
});

在Flask一侧,我有一个简单的函数,该函数呈现一个显示JSON对象的HTML页面:

On the Flask side, I have a simple function that renders an HTML page displaying the JSON object:

@app.route('/create', methods=['POST'])
def create():
    content = request.json
    print content
    return render_template('string.html', string = content)

我知道正在传递JSON,因为我可以看到它打印在运行Flask服务器的控制台中:

I know the JSON is being passed, because I can see it printed in the console running the Flask server:

问题在于模板是作为Ajax请求响应的一部分呈现的,但是我希望将模板呈现为新的html页面:

推荐答案

因此,事实证明,我实际上不需要使用jQuery,相反,我可以仅使用带有隐藏字段的html表单提交JSON(如提示所示)在问题中):

So it turns out I actually didn't need to use jQuery for this, instead I can submit JSON simply using an html form with a hidden field (as hinted at in this question):

<div id="form">

      <form id="send" method="post" action="create" onsubmit="getJSON()" enctype='application/json'>        
        <input type="submit" value="Continue" />
        <input type="hidden" name="jsonval" value=""/>
      </form>
</div>

然后在单击按钮时使用javascript填充表单:

And then use javascript to populate the form when the button is clicked:

function getJSON(){

            json = geojson.write(vectors.features);
            var formInfo = document.forms['send'];
            formInfo.jsonval.value = json;

        }

这篇关于如何从ajax POST表单提交使用Flask的render_template的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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