Cof*_*use 13 javascript http-post
补充:我不能使用jQuery.我使用的是西门子S7控制单元,它有一个小的网络服务器,甚至无法处理80kB的jQuery文件,所以我只能使用原生的Javascript.从这个链接Ajax请求与JQuery页面卸载我得到我需要使请求同步而不是异步.可以用原生Javascript完成吗?
我从这里复制了代码:JavaScript发布请求,如表单提交
我想知道是否可以在关闭窗口/选项卡时调用它/使用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();
}
Run Code Online (Sandbox Code Playgroud)
这是一种方法:
<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>
Run Code Online (Sandbox Code Playgroud)
请注意,请求可能必须是同步的(调用request.open带async=false).
另一个引人注目的关注点:
如果客户端突然终止(例如,浏览器以"结束进程"或"断电"关闭),则onunload事件和将onbeforeunload不会被触发,并且请求将不会被发送到服务器.
| 归档时间: |
|
| 查看次数: |
6360 次 |
| 最近记录: |