为什么我不能使用jQuery火从卸载事件处理Ajax请求? [英] Why can't I use jQuery to fire an AJAX request from an unload event handler?
问题描述
我有以下的code,打算当用户关闭聊天窗口记录事件:
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');
}
无论是你好和成功的消息警告罚款,但在AJAX回调警报不......我打算通过AJAX请求触发的操作也不会发生(我开发一个聊天应用程序,并打算登录的数据库中的条目,当用户关闭窗口)。
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).
推荐答案
由于阿贾克斯是异步的,页面被卸载之前,响应被正确发送,有效地终止连接。尝试设置异步:假;
,虽然这会耽误卸载页面收到后的反应,这不是很大的用户体验,如果你的服务器运行缓慢,直到
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');
}
这篇关于为什么我不能使用jQuery火从卸载事件处理Ajax请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!