1

我正在尝试在“beforeunload”事件上对服务器进行 JSONP 调用。在我开始使用后退按钮之前,这一切都很好。如果我离开页面然后在下次调用 beforeunload 事件时按“返回”,它似乎发出 JSONP 请求,但服务器从未收到它。

注意(1):这已经在 IE 和 FF 上测试过(问题出现在两者上)。

注意(2):我也使用 jQuery.getJSON 方法进行了测试,它有同样的问题,所以我认为 makeJSONPCall 函数是正确的。(我可能是错的)

有什么想法吗?

一些上下文代码:

JSONP 调用:

makeJSONPCall('http://serverurl.mvc/method?args=' + data, 'callbackfunction');      

function makeJSONPCall(url, callbackname)
{                
  if (url.indexOf("?") > -1) url += "&jsonp=" 
  else url += "?jsonp=" 
  url += callbackname + "&";
  url += new Date().getTime();
  var script = document.createElement("script");            
  script.setAttribute("id", "JSONP");
  script.setAttribute("src",url);
  script.setAttribute("type","text/javascript");                
  if (document.head) document.head.appendChild(script);
  else document.body.appendChild(script);    
}

谢谢

4

2 回答 2

0

那个事件有点古怪。您可能最终决定不使用它。首先,确保您正在发布同步帖子。接下来,您可能需要向用户展示一个 UI,以防止浏览器过快更改位置。我曾经使用过类似下面的东西并且它有效,但我最终以不同的方式做事。

    window.onbeforeunload = function() {
               // stuff do do before the window is unloaded here.
               if(IsDirty()) {
            //i only want to call ajax if I need to.
                setTimeout(function(){
                    DoAjaxSaveSynchronously (); // this was important
                    ClearDirty();
                        }, 500);
//this return value causes the browser to pop a modal window.
                return "You have unsaved work. Please stay on this page to save your work.";
               }
            }
于 2009-11-18T23:14:26.913 回答
0

我正在研究一个类似的问题 - 我必须发送数据以响应用户离开网站,并且我的代码作为外部资源存在于某人的页面中。我无法弹出任何内容,我必须拨打电话。而且我必须使用不能同步的 JSONP。

我能够弄清楚的是:

  • onbeforeunload 处理程序阻止浏览器破坏当前页面
  • 如果您不返回任何内容,则不会出现弹出窗口。

因此,只要事件处理程序运行,您的代码就会工作。

伪代码:

window.onbeforeunload = function() {
  startAsynchronousSending();
  //do lots of slow and synchronous stuff to delay destroying the window//
  //return statement deliberately missing
}

目前它已经对我有用,但延迟部分只是一个 CPU 密集型循环。它确实有所作为(有足够的时间发送请求),但我正在寻找更好的延迟。

另见:http ://forums.thedailywtf.com/forums/t/24374.aspx

我将不胜感激有关将什么放入循环的想法的评论。我正在考虑一些选项:

  • 在大量数学上浪费 CPU
  • 访问localstorage(同步调用,IO操作)
  • 访问 DOM
  • 同步 ajax 调用(但我不想在不使用它的脚本中包含 ajax 代码)

有任何想法吗?

于 2012-04-02T09:46:56.450 回答