繁体   English   中英

如何在不刷新页面的情况下将 python output 发送回 html?

[英]How to send python output back to html without refreshing the page?

所以我试图制作一个代码编辑器并处理来自用户输入的代码,就像大多数竞争性编码网站的工作方式一样。 我将展示相关部分。

I used codemirror along with Flask on python, make a code editor in the page, using js to get the user input from a button onclick and using ajax to send the code back to my python script, and say I processed my data and produced an output,现在我坚持尝试将数据发送回 html 页面(可能就像在另一个代码块中向用户显示 output 一样)

html 代码块的代码,我尝试发回数据:py-tut.html

        <div class="codeblock">
            <p>Python editor</p>
            <code><textarea type="text" class="code" id="code" spellcheck="false"></textarea></code>
            <script>
                var codebox = CodeMirror.fromTextArea(document.getElementById("code"), {
                    mode: "python",
                    theme: 'dracula',
                    indentUnit: 4,
                    lineNumbers: 1
                });
                {#set any values in the text box#}
                codebox.getDoc().setValue("import random")
            </script>
            <div class="console" id="console"></div>
            <button type="submit" class="submit" onclick="submit()">Submit</button>
            <script>
                function submit() {
                    var c = codebox.getValue()
                    $.post('http://127.0.0.1:8000/get_code/', {c}, function(){
                        {#this is the part where Im stuck at#}
                        document.getElementById("console").innerHTML = {{ code }};
                    })
                }
            </script>
        </div>

这是 Flask 部分的代码:website.py

@app.route("/get_code/", methods=["GET", "POST"])
def get_code():
    if request.method == "POST":
        code = request.form.getlist('c')[0]
        print(code)
        return render_template("py-tut.html", code = "code")

以下是该网站的实际外观: 在此处输入图像描述

主要问题是处理后我无法将数据发送回 html,我尝试了 render_template、url_for、redirect,但每次单击提交按钮时,都没有任何反应。 请帮忙

这是一个简短的、未经测试的版本。 它依赖于 JQuery 库。

您的页面的以下脚本部分可以从 onclick 事件中触发。 它运行一个获取请求。 它应该获取您的用户输入的代码,或者您希望传输到后端的任何内容。 它是 POST 数据,因此内容将包含在请求中(如 JSON 使用stringify )。

<script>
  let api_submit = function() {
    fetch('{{ url_for('get_code') }}', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json;charset=utf-8'
      },
      body: JSON.stringify($('.code').html())
    })
    .then( response => response.json() )
    .then( function (result) {
      $('.console').html(result.code);
    });
  };
</script>

这是您处理 POST 数据的后端路由。 内容需要从 JSON 转换而来。 flask render_template 使用 Jinja 构造响应,然后此响应数据以 python dict(一个称为 'code' 的 dict 元素)的形式发送回客户端。 方便的是,在 flask 中,在服务器对该 POST 请求的响应中,dict 会自动转换为 JSON。

@app.route("/get_code/", methods=["GET", "POST"])
def get_code():
  if request.method == "POST":
    post_data = request.get_json()
    code = post_data.get('code')
    return dict(code=render_template("py-tut.html", code=code))
  # you may need to cater for 'GET' accesses from somewhere

看看这是否有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM