為什么我不能使用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”


注意!

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



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