用户离开页面时如何检测表单中未保存的数据? [英] How to detect unsaved data in form when user leaves the page?

查看:306
本文介绍了用户离开页面时如何检测表单中未保存的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户离开页面而不提交表单时,我需要检测表单中未保存的数据.我想在不向每个输入添加值更改侦听器的情况下实现这一点.

I need to detect unsaved data in form when user leaves the page without submitting the form. I would like to implement that without adding a value change listener to each input.

这是功能要求:

如果页面中的值更改了警报消息弹出窗口,通知用户他需要保存更改的数据,但用户未打开任何页面,则用户打开页面比单击任何链接都快."

"User open a page than click on any link if values in the page changed an alert message popup to notify user that he need to save changed data, but if did not change any thing system continue without notify user".

我试图比较数组方法,以比较DB的DTO和绑定DTO,但是这给我带来了数组长度和字节比较方面的许多问题.

I tried to compare array method to compare both DTO coming for DB and the bind DTO, but it gives me a lot of problems in array length, and byte comparison.

推荐答案

这通常是在JavaScript的帮助下在客户端实现的,因为最终用户无法很好地在服务器端拦截beforeunload事件离开页面.

This is normally implemented in the client side with help of JavaScript, because it's not nicely possible to intercept on beforeunload event from the server side on when the enduser leaves the page.

这是在JavaScript库 jQuery 的帮助下的一个具体示例(否则,最终您将得到10倍的代码,以使其能够正确地跨浏览器兼容并与ajax重新渲染无缝配合):

Here's a concrete example with help of the JavaScript library jQuery (otherwise you would end up with 10 times as much code to make it properly crossbrowser compatible and work seamlessly together with ajax re-renders):

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
    $(function() {
        // Set the unload message whenever any input element get changed.
        $(':input').on('change', function() {
            setConfirmUnload(true);
        });

        // Turn off the unload message whenever a form get submitted properly.
        $('form').on('submit', function() {
            setConfirmUnload(false);
        });
    });

    function setConfirmUnload(on) {
        var message = "You have unsaved data. Are you sure to leave the page?";
        window.onbeforeunload = (on) ? function() { return message; } : null;
    }
</script>

只需将其粘贴到您的<h:head>模板中,或将其放入<h:outputScript>所包含的某些script.js文件中即可.

Just paste this in your <h:head> template or just put it in some script.js file which you include by <h:outputScript>.

这篇关于用户离开页面时如何检测表单中未保存的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆