规格:
我的代码是:
window.onbeforeunload = function (e) {
e = e || window.event;
if (e) {
e.returnValue = 'Sure?';
}
$.ajax({
url: '/api/Electronic/leave',
dataType: "json",
contentType: "application/json",
cache: false,
type: 'POST',
data: myData,
success: function (data) {
//how to leave this page?
},
error: function () {
console.log("Error");
}
});
return 'Sure?';
};
答案 0 :(得分:0)
- 当用户离开页面并等待结果时,您可以执行同步ajax调用
window.onbeforeunload=function(e){
var result = false;
$.ajax({
url: 'https://api.github.com/users/mralexgray/repos',
type: 'GET',
async: false,
success: function (data) {
//do whatever you want here
for (var i = 0; i < 10000;i++){
console.log(i);
}
result = true;
},
error: function (e) {
console.log("error");
}
});
if (result) {
window.onbeforeunload = window.thisPage.closeEditorWarning;
} else {
var confirmationMessage = 'Somthing went wrong. If you leave your changes will be lost.';
(e || window.event).returnValue = confirmationMessage;
return confirmationMessage;
}
}
答案 1 :(得分:0)
当用户确认“离开此页面”(发送ajax请求并等待收到响应)时执行操作。
那是不可能的。当用户确认“离开此页面”时,您的脚本将被终止。