本文介绍了jQuery在window.unload上的帖子(窗口或浏览器关闭)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无论用户以哪种方式离开页面,我都需要发送发布请求.到目前为止,这是我所拥有的,但是它不起作用:

I need to send a post request when the user leaves the page in whichever way. So far this is what i have, but it's not working:

$(window).unload(function(){        
 $.post("http://localhost/project/quizTime.php",{action:"updateTime",userID:userid,quizID:quizid,newTime:currentTime*1000,rand:Math.random()},function(time)
    {
    });
});

通过用click函数替换window.unload测试了PHP代码.效果很好,可以根据需要更新所有内容,这意味着问题出在$(window).unload触发器.

the PHP code was tested by replacing window.unload with a click function. That works perfectly and updates everything as needed, which means the problem is with that $(window).unload trigger.

推荐答案

您必须使用ajax方法,并将异步选项设置为false,例如:

You must use ajax method with async option set false, like this:

$.ajax({
    type: 'POST',
    async: false,
    url: 'YOUR_URL',
    data: 'YOUR_DATA'
});

通过这种方式,浏览器在完成其他操作之前会等待请求完成.

In this way browser wait for the request to finish before doing anything else.

这篇关于jQuery在window.unload上的帖子(窗口或浏览器关闭)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 18:47