为什么我不能使用jQuery从卸载事件处理程序中触发AJAX请求?

[英]Why can't I use jQuery to fire an AJAX request from an unload event handler?


I have the following code, intended to log the event when a user closes a chat window:

我有以下代码,用于在用户关闭聊天窗口时记录事件:

$(window).unload( function() {
   test();
});

function test()
{
   alert("Hi");
   $.ajax({
      type: "POST",
      url: baseUrl + 'Index/test',
      data: "user_id=" + "Nisanth" + "& chat_id=" + 2,
      success: function(msg){
         alert(msg);
      }
   });
   alert('Success');
}

Both the "Hi" and "Success" messages alert fine but the alert in the AJAX callback doesn't... The operation I intend to trigger via the AJAX request is also not happening (I'm developing a chat application, and intend to log an entry in the database when the user closes the window).

“Hi”和“Success”消息都提示良好,但是AJAX回调中的警告没有……我打算通过AJAX请求触发的操作也没有发生(我正在开发一个聊天应用程序,并打算在用户关闭窗口时在数据库中记录一个条目)。

2 个解决方案

#1


15  

Because the ajax is asynchronous, the page is unloading before the response is properly sent, effectively terminating the connection. Try setting async:false;, although this will delay unloading the page until after the response is received, which isn't great for user experience if your server is running slow.

因为ajax是异步的,所以在响应被正确地发送之前,页面会被卸载,从而有效地终止连接。尝试设置async:false;尽管这会将卸载页面延迟到收到响应之后,但如果服务器运行缓慢,这对用户体验不是很好。

$(window).unload( function () { 
    test(); 
}); 
function test() 
{ 
    alert("Hi"); 
    $.ajax({ 
    async: false,
    type: "POST", 
    url: baseUrl + 'Index/test', 
    data: "user_id=" + "Nisanth" + "& chat_id=" + 2, 
    success: function(msg){ 
            alert(msg); 
        } 
    }); 
    alert('Success'); 
} 

#2


-4  

the problem is the format of your data. It is converted to a query string, it must be Key/Value pairs something like: "user_id:value"

问题在于数据的格式。它被转换为一个查询字符串,它必须是键/值对,比如:“user_id: Value”

智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2010/02/16/7204ce03589edf57e02aac1b0879fcb0.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告