首页 > 解决方案 > 如何在 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 吗?我应该怎么做才能让它工作?

标签: ajaxsynchronousonunload

解决方案


推荐阅读