Sending a post Request with Javascript on unload/beforeunload. Is that possible? [duplicate]

北城以北 提交于 2019-12-18 14:48:47

问题


Added: I cannot use jQuery. I am using a Siemens S7 control unit which has a tiny webserver that cannot even handle a 80kB jQuery file, so I can only use native Javascript. from this link Ajax request with JQuery on page unload I get that I need to make the request synchronous instead of asynchronous. Can that be done with native Javascript?

I copied the code from here: JavaScript post request like a form submit

I was wondering if I could call this on closing the window/tab/leaving the site with jquery beforeunload or unload. Should be possible, right?

function post_to_url(path, params, method) {
    method = method || "post"; // Set method to post by default if not specified.

    // The rest of this code assumes you are not using a library.
    // It can be made less wordy if you use one.
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    for(var key in params) {
        if(params.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
         }
    }

    document.body.appendChild(form);
    form.submit();
}

回答1:


Here is one way to do it:

<body onunload="Exit()" onbeforeunload="Exit()">
    <script type="text/javascript">
        function Exit()
        {
            Stop();
            document.body.onunload       = "";
            document.body.onbeforeunload = "";
            // Make sure it is not sent twice
        }
        function Stop()
        {
            var request = new XMLHttpRequest();
            request.open("POST","some_path",false);
            request.setRequestHeader("content-type","application/x-www-form-urlencoded");
            request.send("some_arg="+some_arg);
        }
    </script>
</body>

Note that the request probably has to be synchronous (call request.open with async=false).

One additional notable point of attention:

If the client is terminated abruptly (e.g., browser is closed with "End Process" or "Power Down"), then neither the onunload event nor the onbeforeunload will be triggered, and the request will not be sent to the server.



来源:https://stackoverflow.com/questions/21228349/sending-a-post-request-with-javascript-on-unload-beforeunload-is-that-possible

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