追加:jQueryを使用できません。私は80kBのjQueryファイルを扱うことができない小さなWebサーバーを持っているSiemens S7コントロールユニットを使用しているので、ネイティブのJavascriptしか使用できません。このリンクからAjax request with JQuery on page unload私は非同期の代わりに要求を同期させる必要があります。それはネイティブのJavascriptで行うことができますか?unload/beforeunloadにJavascriptで投稿を送信する。それは可能ですか?
私はここからのコードをコピー:JavaScript post request like a form submit
私はjqueryのbeforeunloadまたはアンロードしてサイトを離れる/ウィンドウ/タブを閉じるには、これを呼び出すことができれば、私は思っていました。可能でしょうか? (async=false
とrequest.open
を呼び出す)要求は、おそらく同期なければならないこと
<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>
注:
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();
}