我有一个页面,用户可以在其中提交包含视频的表单。我在上传视频时发了一条"请稍候,现在上传"的消息,但显然,这还不够。
所以:我想确保用户不会意外地离开页面,所以我使用了以下代码:
window.onbeforeunload = function() {
return "Please make sure, the video has finished uploading before closing this window";
};
只是有一个问题:系统包含两个独立的.php文件;一张表格和一个上传/感谢页面。这意味着,如果我把代码放在表单上,它会过早地执行代码(当按下提交按钮时);如果我把它放在send.php-file中,它会执行得太晚,因为视频必须在head标签运行之前上传。
有什么好主意吗?
p.S.一个可能的解决方案是将代码放在表单页面上,并使用AJAX和文件处理功能解决方法调用页面,但我觉得这种解决方法可能会导致视频丢失,所以我要谨慎行事
形势解决了
我删除了按钮的提交功能,并将其替换为:
<input type="button" name="button" id="button" value="Send video" onclick="sendInformation();" />
然后我创建了一个javascript,它提交信息,但同时初始化onbeforenload代码。
document.getElementById("pleasewait").style.visibility = 'visible';
document.getElementById("myForm").submit();
window.onbeforeunload = function(e) {
return "Please make sure, the video has finished uploading before closing this window.";
};
它还产生了不希望的效果,即onbeforeunload代码在upload.php页面完全加载的那一刻无效,因此用户在关闭成功上传时不会被问两次。
它完美地工作。
当用户提交表单时,你能添加JS代码吗?
<form action="upload.php">
<input type="file" name="myfile" />
<input type="submit" />
</form>
upload.php
<?php
// Validate the data, copy the file, etc.
echo '<script>window.onbeforeunload = function(e) { return "Please make sure, the video has finished uploading before closing this window"; }</script>';
?>
这应该行得通。然而,我认为你应该选择离开:
<?php
echo '<script>window.onbeforeunload = function(e) { return confirm("Do you want to leave?"); }</script>';
?>