【问题标题】:How to use Flask's render_template from an ajax POST form submit如何从 ajax POST 表单提交中使用 Flask render_template
【发布时间】:2014-09-13 12:33:59
【问题描述】:

我希望得到这个similar question的答案:

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

    <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 页面:

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

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

问题是模板被渲染为Ajax请求响应的一部分,但我希望模板被渲染为一个新的html页面:

【问题讨论】:

  • 你在哪里声明了 var $SCRIPT_ROOT 还是 PHP var?
  • 与本例无关。

标签: jquery python ajax flask


【解决方案1】:

试试这个,

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

    });

【讨论】:

  • 我想在新的 URL 上呈现模板,而不是在同一页面上。
  • 我所见过的任何示例都没有包含这个简单的最后成功行,但他们都声称成功呈现下一个交互式页面。他们不工作!!!你的。这是一个救生员。
【解决方案2】:

所以事实证明我实际上不需要为此使用 jQuery,而是可以简单地使用带有隐藏字段的 html 表单提交 JSON(如 this 问题中所暗示的那样):

<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 填充表单:

function getJSON(){

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

        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-24
    • 2017-11-22
    • 1970-01-01
    • 2015-05-21
    • 1970-01-01
    • 1970-01-01
    • 2021-09-02
    • 1970-01-01
    相关资源
    最近更新 更多