今天在作日新图库的时候遇到个问题,用户上传模块中,上传是用了一个SWFUpload的上传插件,上传是ajax实现html
的,假设用户上传了图片,并无提交图集,而是离开了页面,关闭浏览器或者刷新了页面,服务器上会留下ajax
不少垃圾,在网上找了个js的解决方法,首先判断用户离开页面刷新或关闭,而后使用ajax删除服务器上的图浏览器
片。服务器
js判断离开页面刷新或关闭的方法:(转自:http://blog.sina.com.cn/s/blog_45b088420100gahi.html)测试
一个判断页面是否真的关闭和刷新的好方法:ui
window.onbeforeunload=function (){
alert("===onbeforeunload===");
if(event.clientX>document.body.clientWidth && event.clientY < 0 || event.altKey){
alert("你关闭了浏览器");
}else{
alert("你正在刷新页面");
}
}
这段代码就是判断触发onbeforeunload事件时,鼠标是否点击了关闭按钮,或者按了ALT+F4来关闭网页,若是是,则认为系统是关闭网页,不然在认为系统是刷新网页。url
onbeforeunload与onunload事件
Onunload,onbeforeunload都是在刷新或关闭时调用,能够在<script>脚本中经过window.onunload 来指定或者在<body>里指定。区别在于onbeforeunload在onunload以前执行,它还能够阻止onunload的执行。
Onbeforeunload也是在页面刷新或关闭时调用,Onbeforeunload是正要去服务器读取新的页面时调用,此时还没开始读取;而 onunload则已经从服务器上读到了须要加载的新的页面,在即将替换掉当前页面时调用。Onunload是没法阻止页面的更新和关闭的。而 Onbeforeunload 能够作到。spa
页面加载时只执行onload
页面关闭时先执行onbeforeunload,最后onunload
页面刷新时先执行onbeforeunload,而后onunload,最后onload。firefox
一、onbeforeunload事件:
说明:目前三大主流浏览器中firefox和IE都支持onbeforeunload事件,opera还没有支持。
用法:
·object.onbeforeunload = handler
·<element onbeforeunload = “handler” … ></element>
描述:
事件触发的时候弹出一个有肯定和取消的对话框,肯定则离开页面,取消则继续待在本页。handler能够设一个返回值做为该对话框的显示文本。插件
触发于:
·关闭浏览器窗口
·经过地址栏或收藏夹前往其余页面的时候
·点击返回,前进,刷新,主页其中一个的时候
·点击 一个前往其余页面的url链接的时候
·调用如下任意一个事件的时候:click,document write,document open,document close,window close ,window navigate ,window NavigateAndFind,location replace,location reload,form submit.
·当用window open打开一个页面,并把本页的window的名字传给要打开的页面的时候。
·从新赋予location.href的值的时候。
·经过input type=”submit”按钮提交一个具备指定action的表单的时候。
能够用在如下元素:
·BODY, FRAMESET, window
平台支持:
IE4+/Win, Mozilla 1.7a+, Netscape 7.2+, Firefox0.9+
示例:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>onbeforeunload测试</title>
<script>
function checkLeave(){
event.returnValue="肯定离开当前页面吗?";
}
</script>
</head>
<body onbeforeunload="checkLeave()">
</body>
</html>
二、onunload事件
用法:
·object.onbeforeunload = handler
·<element onbeforeunload = "handler"></element>
描述:
当用户关闭一个页面时触发 onunload 事件。
触发于:
·关闭浏览器窗口
·经过地址栏或收藏夹前往其余页面的时候
·点击返回,前进,刷新,主页其中一个的时候
·点击 一个前往其余页面的url链接的时候
·调用如下任意一个事件的时候:click,document write,document open,document close,window close ,window navigate ,window NavigateAndFind,location replace,location reload,form submit.
·当用window open打开一个页面,并把本页的window的名字传给要打开的页面的时候。
·从新赋予location.href的值的时候。
·经过input type=”submit”按钮提交一个具备指定action的表单的时候。
示例:
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>onunload测试</title> <script> function checkLeave(){ alert("欢迎下次再来!"); } </script> </head> <body onunload="checkLeave()"> </body> </html>