Python Flask:返回 HTML 内容

use*_*275 4 html javascript python string flask

我正在尝试为我自己的个人使用准备一个临时工具,我根本没有后端开发经验。所以我的方法可能是非常规的。虽然可能有更好的方法来解决这个问题

考虑我的 html 文件中的以下片段:

<tr><td>
    <button id="socks.shirt.pants"> dummy text here </button>
</td></tr>
Run Code Online (Sandbox Code Playgroud)

我的目标,就像我可以说的那样简单,就是单击 BUTTON 并使用 Flask 在 python 中的 ID 属性中返回字符串文本。下面是我正在使用的代码。

app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
    #display html file
    return send_from_directory('','myfile.html')
    #this is the part that needs help
    textdata = request.htmlcontent.td.id
Run Code Online (Sandbox Code Playgroud)

我尝试了几种不同的方法来提取 html 内容。包括但不仅限于:

request.html.tr.id,
request.get_data(),
request.data(),
request.form,
Run Code Online (Sandbox Code Playgroud)

我现在明白 request.form 返回以表单提交的用户提供的信息,这对我不起作用,因为我想要检索的信息将被硬编码到允许此过程工作的任何标签下的 html 文件中。(当前 tr -> td -> 按钮)。我相信,其他方法要么返回 None 要么返回一些空字符串。

另外,我想知道除了 Flask 之外,是否还有一些 javascript 代码需要使用?我希望问这个问题不是不切实际的期望!任何建议都会有很大帮助!

Aja*_*234 5

你可以用ajaxjquery

在 main 中filename.py,包含一个这样的路由,它访问json来自前端响应的参数。此外,提供一个将呈现 HTML 模板的路由:

@app.route('/recieve_data')
def get_id():
  the_id = flask.request.args.get('button_id')
  return "<p>Got it!</p>"

@app.route('/', methods=['GET', 'POST'])
def home():
  return flask.render_template('filename.html')
Run Code Online (Sandbox Code Playgroud)

在您的 HTML(存储在 中filename.html)中,使用以下代码:

<html>
  <head>
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  </head>
  <body>
    <tr><td>
     <button id="socks.shirt.pants" type='button'> dummy text here</button>
     <div id='response'></div>
    </td></tr>
  </body>
  <script>
   $(document).ready(function() {
      $("button").click(function(event){
         var the_id = event.target.id;
         $.ajax({
            url: "/recieve_data",
            type: "get",
            data: {button_id: the_id},
           success: function(response) {
           $("#response").html(response);
         },
          error: function(xhr) {
        //Do Something to handle error
        }
       });
     });
   });
  </script>
</html>
Run Code Online (Sandbox Code Playgroud)

xxxxxxxxxxxx