补充说明:我无法使用jQuery。我正在使用西门子S7控制器,它有一个微小的Web服务器,甚至不能处理80KB的jQuery文件,因此我只能使用本机Javascript。从这个链接Ajax request with JQuery on page unload中,我得知需要将请求同步而不是异步。是否可以使用本机Javascript完成?
我从这里复制了代码:JavaScript post request like a form submit
我想知道在使用jquery的beforeunload或unload关闭窗口/选项卡/离开站点时是否可以调用此代码。这应该是可能的,对吧?
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();
}
beforeunload
和unload
事件中使用sendBeacon
。 - Alec