简体   繁体   English

没有按钮时,如何防止获取请求重新加载 Javascript 中的页面?

[英]How to prevent a fetch request from reloading the page in Javascript when there is not a button?

Let me preface this by saying there are endless threads that describe the issue WITH a button involved.让我先说有无穷无尽的线程来描述涉及按钮的问题。 Usually it's solved by just calling event.preventDefault() on the event you pass in. But what if the post request is called after something happens that isn't within the user's control, for instance, after a certain amount of frame?通常它可以通过在你传入的事件上调用 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;
      }

With this code, I want to call makeScore only after loadNextLevel is called, and that is only getting called when a level is completed.使用此代码,我只想在调用 loadNextLevel 后调用 makeScore,并且仅在完成关卡时调用。 But, currently the score is saved, and the page is refreshed.但是,当前分数已保存,页面已刷新。 How can I prevent this refresh?我怎样才能防止这种刷新?

Edit: added scores controller below编辑:在下面添加分数 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

Edit #2 - Adding the function that it apparently gets stuck on after the fetch is completed.编辑 #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;
}

I had this same issue, in my case the problem was caused by the live server.我遇到了同样的问题,在我的情况下,问题是由实时服务器引起的。 I had in the same folder the client (HTML,CSS, JS, etc.) and the database (I was using the json-server extension).我在同一个文件夹中有客户端(HTML、CSS、JS 等)和数据库(我使用的是 json-server 扩展)。 The problem was that the live server was detecting the changes in the db.json file.问题是实时服务器正在检测 db.json 文件中的更改。 When fetch post or delete data, it triggers the live reload in the live server extension.当获取发布或删除数据时,它会触发实时服务器扩展中的实时重新加载。 So I solved it by dividing the folders and opening them separately in vs code, then, inside the client folder, run live server and it worked perfectly.所以我通过划分文件夹并在 vs 代码中分别打开它们来解决它,然后在客户端文件夹中运行实时服务器,它运行良好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何防止页面在 JavaScript 获取帖子请求后刷新? - How to prevent page from refreshing after JavaScript fetch post request? 允许表单发送 POST 请求但阻止页面重新加载 - Javascript - Allow form to send POST request but prevent page from reloading - Javascript 在弹出窗口中单击退出按钮时,防止重新加载父页面 - Prevent Parent page from reloading when exit button is clicked in popup 如何防止ajax请求重新加载页面 - How can i prevent ajax request from reloading page 如何防止Backbone应用程序中的“后退”按钮重新加载页面 - How to prevent Back button from reloading page in Backbone app 如何防止多文档表单页面重新加载? - How to prevent multidocument form page from reloading? 如何防止跳转链接重新加载同一页面? - How to prevent jumplinks from reloading the same page? 使用JavaScript阻止刷新/重新加载页面 - Prevent refreshing / reloading a page with JavaScript 试图弄清楚如何执行 ajax 调用以防止提交按钮重新加载整个页面 - trying to figure out how to perform an ajax call to prevent submit button from reloading entire page 如何防止每次单击按钮时重新加载javascript? - How do I prevent a javascript from reloading every time a button is click?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM