阻止网页加载直到JQuery AJAX调用完成?

时间:2013-08-14 21:20:48

标签: javascript jquery ajax onload-event

我对遗留网站的要求无法重新设计屏幕,我无法使用标头无缓存标签,我必须阻止用户在退出并按下后退按钮后才能看到缓存的屏幕。

我差不多要解决了(见下面的代码位)

当页面加载时,我使用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>

我不喜欢这个解决方法的一件大事是,我可以在JQuery函数完成之前暂时完成内容。

有没有办法可以阻止页面加载/渲染,直到JQuery AJAX函数停止?

由于


更新:答案:


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

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

});

1 个答案:

答案 0 :(得分:6)

您可以使用ajax函数将async属性设置为false来执行此操作。

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