[英]How to prevent page from refreshing after JavaScript fetch post request?
[英]How to prevent a fetch request from reloading the page in Javascript when there is not a button?
讓我先說有無窮無盡的線程來描述涉及按鈕的問題。 通常它可以通過在你傳入的事件上調用 event.preventDefault() 來解決。但是如果在用戶無法控制的事情發生之后調用發布請求怎么辦,例如,在一定數量的幀之后?
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,並且僅在完成關卡時調用。 但是,當前分數已保存,頁面已刷新。 我怎樣才能防止這種刷新?
編輯:在下面添加分數 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 在獲取完成后它顯然卡住了。
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 代碼中分別打開它們來解決它,然后在客戶端文件夾中運行實時服務器,它運行良好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.