Sending a request back to server in onbeforeunload event

懵懂的女人 提交于 2019-12-13 02:10:33

问题


When a user edits a record in my application I track that they have it 'locked' to prevent another user from editing it until the first user closed the window (or saves).

I'm trying to send the request back to the server to unlock the record but it's not working in Firefox. The onbeforeunload event is called in script but it's not sending back the request to the server. Any ideas?

<body>
<script>
    window.onbeforeunload = function (e) {
        doUnlock();
    }

function doUnlock() {
    if (navigator.appName == 'Microsoft Internet Explorer') {
        // works in IE (with an IFRAME)
        utilFrame.location.href = "/unlock.do?recordId=" + recordId;
    } else if (navigator.appName == 'Netscape') {
        // None of this works....
        //window.location.href = "/unlock.do?recordId=" + recordId;
        var req = newXMLHttpRequest();
        req.open("GET", "/unlock.do?recordId=" + recordId, true);
        req.send();
    } else {
        // Works for chrome
        window.open("/unlock.do?recordId=" + recordId);
    }
}

</script>

回答1:


Add a space between new and XMLHttpRequest.

On page unload, any pending (AJAX) requests are *cancelled. If you have to send an AJAX request to the server on unload, use a synchronous request (not recommended!!!):

    var req = new XMLHttpRequest();
    req.open("GET", "/unlock.do?recordId=" + recordId, false); // false
    req.send();

I do not recommend the synchronous request, because the user interface blocks until the request has finished. That's not very user-friendly.




回答2:


You should look into using a time based lock. When a user starts editing a record lock it with a timestamp. Every 30 seconds send a ping from the user that the record should still be locked. If there is no ping for 60 seconds unlock the record.



来源:https://stackoverflow.com/questions/9350900/sending-a-request-back-to-server-in-onbeforeunload-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!