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

后端 未结 2 413
花落未央
花落未央 2020-12-09 13:19

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

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

function test()
{
   al         


        
相关标签:
2条回答
  • 2020-12-09 13:46

    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 讨论(0)
  • 2020-12-09 13:59

    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'); 
    } 
    
    0 讨论(0)
提交回复
热议问题