2009-11-18 81 views
1

我想在'beforeunload'事件上对服务器进行JSONP调用。这一切都很好,直到我开始使用后退按钮。如果我离开页面,然后在下次调用beforeunload事件时按'返回',它看起来会生成JSONP请求,但服务器永远不会收到它。JSONP + onbeforeunload +后退按钮+问题

注意(1):已经在IE和FF上测试过(两者都出现问题)。 (2):我也测试过使用jQuery.getJSON方法,它有同样的问题,所以我认为makeJSONPCall函数是正确的。 (我可能是错的)

任何想法的人?

一些代码方面:

JSONP CALL:

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);  
} 

感谢

回答

0

这一事件是种古怪。你可能最终决定不使用它。首先,确保你正在制作同步帖子。接下来,您可能需要向用户展示用户界面,以防止浏览器过快更改位置。我曾经使用过类似下面这样的东西,但它最终还是以不同的方式做事。

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."; 
       } 
      } 
+0

感谢您的及时回应克里斯。不幸的是,作为公用事业脚本,我不能在人们的网页上发布警报。我其实并不认为这里有解决方案,因为在我收到服务器回复之前,我无法在beforeunload事件中“等待”。 谢谢反正 – gatapia 2009-11-19 00:04:39

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

我很感激上要放什么东西在循环的想法意见。我采取了一些选项考虑:

  • 大数
  • 访问的localStorage(同步调用,IO操作)
  • 访问DOM
  • 同步AJAX调用(但我不就来了数学浪费CPU t想要在不使用它的脚本中包含ajax代码)

任何想法?