无法在页面中获取自定义消息警报,请执行“onbeforeunload”事件

时间:2012-10-15 05:49:06

标签: javascript ajax onbeforeunload

我放下以下脚本以防止离开页面同时处理步骤

<script language="JavaScript">
window.onbeforeunload = confirmExit;

function confirmExit()
{
JQObj.ajax({
    type: "POST",
    url: "<?php echo $this->url(array('controller'=>'question','action'=>'cleaSess'), 'default', true); ?>",
    success: function(data){}
});

return "You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?";
}

</script>

但是每当我收到默认警报消息而不是我设置自定义警报消息时,

我希望在最终用户点击“离开页面”按钮时调用ajax调用,但在上面的脚本中,ajax在单击“离开”按钮之前调用调用,

当且仅当人们离开页面时,任何人都有想法或逻辑来调用ajax。

2 个答案:

答案 0 :(得分:2)

您可以使用“unload”事件发送AJAX请求:

<script type="text/javascript">
    window.onbeforeunload = function() {
        return "You have attempted to leave this page. "
               + "If you have made any changes to the fields without "
               + "clicking the Save button, your changes will be lost. "
               + "Are you sure you want to exit this page?";
    };

    window.onunload = function() {
        // Ending up here means that the user chose to leave
        JQObj.ajax({
            type: "POST",
            url: "http://your.url.goes/here",
            success: function() {}
        });
    };
</script>

另请参阅此 short demo

答案 1 :(得分:0)

你应该尝试这样的事情:

window.onbeforeunload = displayConfirm;

function displayConfirm()
{
    if (confirm("You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?"))
    {
        confirmExit();
    }
}
相关问题