我正在創建一個 Web 應用程式來將資料保存到 MySQL 資料庫。現在我需要在瀏覽器關閉時保存資料。我使用 ajax 函式來呼叫我的 PHP Web 服務。我使用 onunload 事件來檢測瀏覽器關閉事件。我的問題是當瀏覽器關閉時它會觸發 onunload 事件,但不會等到 ajax 函式成功。因為那個資料沒有保存到資料庫中。當我將除錯點放在 onunload 函式上時,它作業正常并將所有資料保存到資料庫中。
這是我嘗試過的。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h1>Testing data save on close event</h1>
</body>
</html>
<script>
window.onunload = function(e) {
console.log("The Window is closing!");
saveDataOnClose();
};
function saveDataOnClose(){
url = URL "savedata.php";
var client = [{firstName: 'John', lastName: 'doe', EmailAddress: '[email protected]'}];
var jObj = JSON.stringify(client);
$.ajax({
url: url,
type: "POST",
data: {
"Client": jObj,
},
success: function (result) {
var Id = result;
localStorage.setItem("result", Id);
},
error: function (xhr, errorType, exception) {
console.log("Store data on remote database", "Storing data on the remote database failed, " xhr.statusText " " xhr.status new Error().stack, false);
}
});
}
</script>
uj5u.com熱心網友回復:
The window.onunloadfunction is an special function, so actually asynchron code can be executed, but will be killed by the browser, when the tab has been closed which happens immediately.
已在此處回答了類似的問題。解決方案可能是服務作業者,即使您的網站沒有打開,它也會在后臺處理資料。
但是,您還可以做的是將資料臨時存盤到localStorage物件中,該物件同步處理資料。
一旦您的用戶在同一設備上回傳您的網站,您就可以檢查是否有任何未保存的更改并將其與您的后端同步。
uj5u.com熱心網友回復:
在您的情況下,請考慮使用該onbeforeunload事件。此事件的作用是,當用戶即將關閉選項卡或重新加載頁面或嘗試離開當前頁面時,它會向用戶顯示一個確認框。
<html>
<body onbeforeunload="return myFunction()">
<a href="https://www.google.com/">Click here to go to Google.com</a>
<script>
function myFunction() {
return "Return anything here.....";
}
</script>
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/359825.html
標籤:javascript 阿贾克斯
