2014-01-20 38 views
8

补充:我不能使用jQuery。我正在使用一个西门子S7控制单元,它具有一个甚至不能处理80kB jQuery文件的小型网络服务器,所以我只能使用本地Javascript。从这个链接Ajax request with JQuery on page unload我得到,我需要使请求同步,而不是异步。这可以用原生Javascript完成吗?在卸载/ beforeunload时发送带有Javascript的帖子请求。那可能吗?

我从这里复制的代码:JavaScript post request like a form submit

我在想,如果我可以称之为上关闭窗口/标签/离开与jQuery beforeunload或卸载该网站。应该可以吧?

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(); 
} 

回答

4

下面是做到这一点的一种方法:

<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> 

注意,请求可能必须是同步的(叫request.openasync=false)。的关注

一个额外显着的点:

如果客户端突然终止(例如,浏览器被关闭了“结束进程”或“掉电”),则既没有onunload事件也不是onbeforeunload将被触发,并且该请求不会被发送到服务器。