javascript 在 JQuery AJAX 调用完成之前停止加载网页?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18242527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:10:56  来源:igfitidea点击:

Stop A Web Page From Loading Until A JQuery AJAX Call Completes?

javascriptjqueryajaxonload-event

提问by Steve

I have requirements for a legacy site where I can't redesign the screens, I can't use header no-cache tags and I have to prevent the user from seeing cached screens after they logged out and pressed their back button.

我对无法重新设计屏幕的旧网站有要求,我不能使用标题无缓存标签,我必须防止用户在注销并按下后退按钮后看到缓存的屏幕。

I am almost to a solution ( see the code bit below )

我快要找到解决方案了(请参阅下面的代码位)

When the page loads, I use a JQuery AJAX function to call the web app and see if the user is still logged in. If not, the user gets redirected to the login screen

当页面加载时,我使用 JQuery AJAX 函数调用 Web 应用程序并查看用户是否仍然登录。如果没有,用户将被重定向到登录屏幕

<html>
<head>
 <!-- all the usual header stuff, plus links to the jQuery libaries, first script tag on page below -->

<script language = "javascript">

 $.get("/acme/confirm_authentication",function(data){
            if( data != "confirmed"){
                location.href = "logout";
            }
  }); 



</script>
</head>
<body>

blah blah blah
</body>
</html>

The big thing I don't like about this workaround is that for a split second I can the content before the JQuery function completes.

我不喜欢这种解决方法的最大的事情是,在 JQuery 函数完成之前,我可以在瞬间获得内容。

Is there a way I can keep the page from loading/rendering until the JQuery AJAX function comes to a stop?

有没有一种方法可以阻止页面加载/呈现,直到 JQuery AJAX 函数停止?

Thanks

谢谢



Update: Answer:

更新: 答案:



I modified the accepted answer below to include a "cache: false" option. In Firefox and Chrome, cached copies of the page that were reached via the back button would run the .ajax(), but would use a cached copy of the variable "data", which would give me an out of date answer.

我修改了下面接受的答案以包含“缓存:假”选项。在 Firefox 和 Chrome 中,通过后退按钮访问的页面缓存副本将运行 .ajax(),但会使用变量“data”的缓存副本,这会给我一个过时的答案。

$.ajax({
 url: "/acme/confirm_authentication",
 async:false,
 cache: false,
 success: function(data) {
     if( data != "confirmed"){
         location.href = "logout";
     }
 }         

});

});

回答by Jean-Philippe Bond

You can do it with the ajaxfunction with the asyncproperty set to false.

您可以ajax使用async属性设置为 false的函数来实现。

  $.ajax({
     url: "/acme/confirm_authentication",
     success: function(data) {
         if( data != "confirmed"){
             location.href = "logout";
         }
     },
     async:false
  });