ajax - 如何在 onunload 函数中向我的服务器发送同步 ajax 请求
问题描述
我需要在网页关闭之前向我的服务器发送一个 ajax 请求,我的发送代码如下。
SendByAajx = function(msg) {
var response;
var xmlHttpReg;
if(window.XMLHttpRequest){
xmlHttpReg = new XMLHttpRequest();
} else if(window.ActiveXObject) {
xmlHttpReg = new ActiveXObject("Microsoft.XMLHTTP");
} else {
throw new Error("Unsupported borwser");
}
if(xmlHttpReg != null) {
xmlHttpReg.open("get", "https://127.0.0.1:57688/test"+'?'+msg, false);
xmlHttpReg.send(null);
if(xmlHttpReg.readyState==4){
if(xmlHttpReg.status == 200) {
var data = JSON.parse(xmlHttpReg.responseText);
if(typeof(data.errorcode) == "number" &&
data.errorcode != 0) {
throw("response error:" + data.errorcode);
}
response = data.result;
} else {
throw new Error("Error");
}
}
}
return response;
}
当我在按钮 onclick 事件中调用此函数时,它可以工作。
function GetOnClick() {
try{
var result = SendByAajx (“data”);
} catch (e) {
//alert(errorInfo);
}
SetButtonDisabled(false);
}
但是当我在页面卸载时调用这个函数时,它不起作用。
<body onload="javascript:OnLoad();" onunload="javascript:OnUnLoad()">
function OnUnLoad() {
try{
var result = SendByAajx(“data”);
} catch (e) {
//alert(errorInfo);
}
}
当我调试应用程序时,JS 执行在此行之后停止:
xmlHttpReg.send(null);
它没有进入下一行:
if(xmlHttpReg.readyState==4)
“数据”也不会发送到服务器。
我的程序有什么问题,可以在 onunload 函数中调用 ajax 吗?我应该怎么做才能让它工作?
解决方案
推荐阅读
- reactjs - 明确这个自定义Formfields react Hook的含义
- windows - Powershell 命令/Windows 进程
- python - Python,所有自变量的散点图
- python - 有没有办法在从 Python 应用程序进行少量编辑后重新运行调用的脚本和函数,而无需关闭并重新启动应用程序?
- c# - 选择最新的两行聊天记录 linq
- ruby-on-rails - Ruby On Rails 和 VueJS 项目部署后所有链接上的 404
- c# - 如果未在表单中选择所有选项,如何停止执行代码
- c# - 如何使用 Moq 测试创建新 DbContext 的方法?
- scala - Scala:是否有可能使用 (x+1) 之类的术语作为案例类模式匹配的参数?
- php - yii2 不保存所有字段