当没有按钮时,如何防止 fetch 请求重新加载 Javascript 页面?

2024-02-28

首先我要说的是,有无数的线程描述了涉及按钮的问题。通常,只需对传入的事件调用 event.preventDefault() 即可解决该问题。但是,如果在发生超出用户控制范围的事件(例如,经过一定量的帧后)后调用 post 请求,该怎么办?

makeScore (userId, gameId, time) {
      fetch('http://localhost:3000/scores', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          time: time,
          user_id: userId,
          maze_id: gameId
        })
      }).catch(error => console.log('ERROR'))
    };

    loadNextLevel(option) {

        console.log("Load Next");

        //  Making a score
        clearInterval(this.interval);
        this.time = document.getElementById('timer_text').innerHTML;
        this.makeScore(this.userId, this.gameId, this.time);
        console.log("Score made");

        if (this.GAMESTATE != GAMESTATE.GAMEOVER) {

        console.log(this.gameObjects);
        document.getElementById('timer_text').innerHTML = "Time"
        this.gameObjects = []
        this.gameIndex += 1;

        console.log(this.gameIndex, this.maxMazes);

        if (option == "new") {
          this.gameIndex = 0;
        }
      }

      if (this.gameIndex >= this.maxMazes) {
        this.gameEnd();
        return;
      }

使用这段代码,我只想在调用 loadNextLevel 之后调用 makeScore,并且只有在关卡完成时才会调用 makeScore。但是,当前分数已保存,并且页面已刷新。我怎样才能阻止这种刷新?

编辑:在下面添加分数控制器

class ScoresController < ApplicationController

    def index
        scores = Score.all
        render json: scores
    end

    def show
        score = Score.find(params[:id])
        render json: score
    end

    def create
        if (params[:user_id] && params[:maze_id])
            user = User.find_by(id: params[:user_id])
            maze = Maze.find_by(id: params[:maze_id])
            score = user.scores.build(time: params[:time], username: user.username)
            maze.scores << score
        end
    end

end

编辑 #2 - 添加在获取完成后显然会卡住的功能。

function setLoggedOutUI() {
  console.log("Log out UI set");
  document.getElementById("timer_text").style.display = "none";
  document.getElementById("logInButton").innerHTML = "Log in";
  document.getElementById("userInfo").innerHTML = "Please Log in to play";
  document.getElementById("logInField").style.display = "inline-block";
  document.getElementById("play").innerHTML = "Log in";
  document.getElementById("scores").style.display = "none";
  document.getElementById("usernameText").style.display = "inline";
  uiSwitch = false;
}

我遇到了同样的问题,就我而言,问题是由实时服务器引起的。我在同一个文件夹中包含客户端(HTML、CSS、JS 等)和数据库(我使用的是 json-server 扩展)。问题在于实时服务器正在检测 db.json 文件中的更改。当获取发布或删除数据时,它会触发实时服务器扩展中的实时重新加载。所以我通过划分文件夹并在 VS Code 中单独打开它们来解决这个问题,然后在客户端文件夹内运行实时服务器,它工作得很好。更多细节here https://stackoverflow.com/a/73872256/19823693

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当没有按钮时,如何防止 fetch 请求重新加载 Javascript 页面? 的相关文章