首先我要说的是,有无数的线程描述了涉及按钮的问题。通常,只需在传入的事件上调用 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。但是,当前分数已保存,并且页面已刷新。如何防止这种刷新?
编辑:在下面添加分数 Controller
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
关于javascript - 当没有按钮时,如何防止 fetch 请求重新加载 Javascript 页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63529298/