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

点击loadOldPlayer按钮触发两次GET请求致模板渲染错误求助

问题:点击按钮触发两次GET请求,导致错误模板渲染

点击loadOldPlayer按钮时,浏览器会发送两次GET请求到/profile接口,本该渲染showsPlayer.html,实际却渲染了playerView.html。

问题截图

前端代码

let playerName
const loadOldPlayer = document.getElementById('playerLoader');

const enterProfile = (usedToLoad) => {
    console.log(playerName)
    if (usedToLoad) {
        playerName = document.getElementById('loadPlayerName').value
    };
    const playerData = {
        playerName: playerName
    };
    const JSONdata = JSON.stringify(playerData);
    fetch(`/profile?tags=${JSONdata}`, { method: "GET" }).then((response) => {
        if (response.ok) {
            document.getElementById('loaderLabel').innerHTML = "Loading Player"
        }
        else {
            alert("Something bad happened.");
        };
    });
};

loadOldPlayer.addEventListener("click", enterProfile.bind(true));

后端Flask代码

from flask import Flask, render_template, request
from static.SNEKfiles import SpaceShipGame
import json


game_app = Flask(__name__)

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

@game_app.route('/profile', methods=['GET'])
def profile():
    if request.method == 'GET':
        playerName = request.args.get('tags')
        if playerName != None:
            print("got the name")
            return render_template("showsPlayer.html")
        else:
            print("here is issue")
            return render_template("playerView.html")

if __name__== "__main__":
    game_app.run(debug=True, host='127.0.0.1', port=7777)

问题原因

  1. 默认表单提交触发额外请求:如果loadOldPlayer按钮嵌套在<form>标签内,点击按钮会自动触发表单的默认GET提交行为,加上手动调用的fetch请求,就会出现两次请求。
  2. bind用法错误:enterProfile.bind(true)把this上下文设为true,并没有正确传递usedToLoad参数——实际传入的是点击事件对象,导致usedToLoad判断失效,playerName未被赋值。第二次请求(默认表单提交)没有携带tags参数,后端返回playerView.html。
  3. 不排除代码中存在重复绑定click事件的情况,导致fetch被调用两次。

修复步骤

1. 阻止默认行为(关键)

如果按钮在表单里,必须阻止默认提交:

loadOldPlayer.addEventListener("click", (e) => {
    e.preventDefault(); // 阻止浏览器默认的表单提交
    enterProfile(true);
});

2. 修正bind传递参数的方式(可选)

如果不想用箭头函数,正确的bind写法是把this放在第一个参数,目标参数放在后面:

loadOldPlayer.addEventListener("click", enterProfile.bind(null, true));

3. 排查重复绑定

检查代码中是否多次调用addEventListener绑定同一个按钮的click事件,避免重复触发fetch。

4. 验证参数传递

在enterProfile里加日志确认usedToLoad和playerName的取值,确保tags参数正确携带到请求中。

修复后,点击按钮只会发起一次带有效参数的GET请求,后端会正确返回showsPlayer.html模板。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 14:24:17