且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用户离开页面时如何检测表单中未保存的数据?

更新时间:2023-12-01 19:39:46

这通常是在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>.