首先我要说的是,有无数的线程描述了涉及按钮的问题。通常,只需对传入的事件调用 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;
}