开发者

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 cha开发者_开发技巧t application, and intend to log an entry in the database when the user closes the window).


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.

$(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'); 
} 


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"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜