不能使用“window.onbeforeunload”来改变网页的位置。 [英] can't change location of webpage using "window.onbeforeunload"

查看:146
本文介绍了不能使用“window.onbeforeunload”来改变网页的位置。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我,当他执行以下操作时,如何发出AJAX请求并将用户发送到其他页面?


  1. 点击下一步,浏览器的前一步骤。

  2. 以任何方式刷新页面(f5,ctrl + r,refresh btn)。关闭浏览器窗口(这里我不想重定向他,只是AJAX请求)。

我想window.onbeforeunload可以让它,

  window.onbeforeunload = function(){
makeAjaxCall();
------
------
}

// Ajax调用成功
函数makeAjaxCall_SuccessHandler(){
window.location.href ='Home.html';
}

但它根本不起作用........
在搜索这个主题后,我发现这是一种为浏览器安全性制定的规则。
,所以请告诉我如何做到这一点或任何其他方式来实现这一目标。

解决方案

你得到的实际行为,所以我有点猜测在这里,但我认为你的问题在于AJAX的异步部分。
您会发现,当您的onbeforeunload处理程序执行时,它可能很好地启动AJAX调用 BUT ,它不会阻止等待其结果返回。相反,执行将继续,onbeforeunload将在您从AJAX请求获得任何结果之前完成(如果有任何调用完成)。

首先添加一些调试痕迹来验证您的处理程序实际上是执行。如果是,请添加一个空闲循环以使其保持忙碌状态(阻止其返回),并查看AJAX调用是否已经完成(我会检查服务器端的)。



如果确实如此,我想你将不得不修改空闲循环来咨询某种标志。或者甚至更好,如果你使用的库允许它,使服务器调用同步。


Can anybody pls tell me, how can i make a AJAX request and send user to some other page when he performs following actions ?

  1. Clicks on next, prev btns of browser.
  2. refresh page by any way(f5,ctrl+r,refresh btn).
  3. try to close browser's window(Here i don't want to redirect him, just AJAX request).

i thought window.onbeforeunload could make it,

  window.onbeforeunload = function () {
    makeAjaxCall();
    ------
    ------
  }

 // Ajax Call is successful
  function makeAjaxCall_SuccessHandler() {
    window.location.href = 'Home.html';
 }

but it is not working at all........ after searching on this topic i found that this is a kind of rule made for browser's security. so pls tell me how to do this or any alternate way to achieve this.

解决方案

You're not describing the actual behavior you're getting so I'm kinda guessing here, but I think your problem here is with the Asynchronous part of AJAX. You see, when your onbeforeunload handler executes it may very well initiate the AJAX call BUT it won't block waiting for its results to return. Instead the execution will continue and onbeforeunload will complete before you ever get any result from your AJAX request (if any call is made at all).

First of all add some debug traces to validate your handler is actually executed. If it is, add an idle loop to keep it busy (preventing it from returning) and see if the AJAX call comes through (I'd check the server side for that).

If that's indeed the case I guess you'll have to modify the idle loop to consult some kind of flag. Or even better, if the libraries you use allow it, make the server call synchronous.

这篇关于不能使用“window.onbeforeunload”来改变网页的位置。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆