You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何点击HTML按钮调用Python Flask函数且不跳转页面?

解决方案:点击按钮显示字母"A"(Flask + HTML)

方法一:纯前端JavaScript实现(无需后端交互)

如果只是单纯点击按钮显示字母"A",直接用前端JS操作DOM是最简洁的方案,不需要后端请求:

修改你的home.html文件:

<html>
  <head>
    <title>GradingGuru</title>
    <style>
      body {
        background-color: rgb(255, 251, 251);
      }
      #display-area {
        margin-top: 20px;
        font-size: 24px;
        font-weight: bold;
      }
    </style>
  </head>
  <body>
    <div id="button"> 
      <button onclick="showLetterA()"> add letter A </button>
    </div>
    <!-- 用来显示字母的区域 -->
    <div id="display-area"></div>

    <script>
      function showLetterA() {
        const displayArea = document.getElementById('display-area');
        // 每次点击替换为A
        // displayArea.textContent = 'A';
        // 每次点击追加一个A
        displayArea.textContent += 'A';
      }
    </script>
  </body>
</html>

方法二:结合Flask后端的AJAX实现(适合需要后端逻辑的场景)

如果需要通过后端获取字母"A"(比如后续有复杂逻辑),可以用AJAX异步请求后端接口:

  1. 修改Flask后端代码:
from flask import Flask, render_template, jsonify

app = Flask(__name__)

@app.route("/")
def home():
  return render_template('home.html')

# 添加返回字母A的接口
@app.route('/get-letter-a')
def get_letter_a():
    return jsonify({'letter': 'A'})

if __name__ == "__main__":
  app.run(host = '0.0.0.0', debug = True)
  1. 修改home.html文件:
<html>
  <head>
    <title>GradingGuru</title>
    <style>
      body {
        background-color: rgb(255, 251, 251);
      }
      #display-area {
        margin-top: 20px;
        font-size: 24px;
        font-weight: bold;
      }
    </style>
  </head>
  <body>
    <div id="button"> 
      <button onclick="fetchAndShowLetterA()"> add letter A </button>
    </div>
    <div id="display-area"></div>

    <script>
      async function fetchAndShowLetterA() {
        try {
          // 异步请求后端接口
          const response = await fetch('/get-letter-a');
          const data = await response.json();
          // 将获取到的字母显示到页面
          const displayArea = document.getElementById('display-area');
          displayArea.textContent += data.letter;
        } catch (error) {
          console.error('获取字母失败:', error);
        }
      }
    </script>
  </body>
</html>

内容的提问来源于stack exchange,提问作者user19669080

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 05:43:37