javascript – 如何在AngularJS中发送HTTP请求onbeforeunload?

我有一个简单的角度应用程序,有两个使用ngRoute加载的视图.当用户在视图之间导航以及用户离开页面时(刷新窗口,关闭选项卡或关闭浏览器),我需要在服务器上进行一些清理.

我的第一站是:Showing alert in angularjs when user leaves a page.它解决用户在视图之间导航的第一种情况.我已经处理了这样的清理:

$scope.$on('$locationChangeStart',function (event) {
    var answer = confirm("Are you sure you want to leave this page?")
    if (answer) {
        api.unlock($scope.id); //api is a service that I wrote. It uses angular $http service to handle communications and works in all other cases.
    } else {
        event.preventDefault();
    }
});

但是,我无法处理用户离开页面的情况.按照上述答案和Google网上论坛帖子:https://groups.google.com/forum/#!topic/angular/-PfujIEdeCY我试过这个:

window.onbeforeunload = function (event) {
    api.unlock($scope.id); //I don't necessarily need a confirmation dialogue,although that would be helpful. 
};

但它没有用.然后我在这里读到:How to execute ajax function onbeforeunload?请求需要同步,这里:How to $http Synchronous call with AngularJS Angular不支持这个(虽然这个可能已经过时了).

我也试过直接调用$http(没有服务),但这也没有用.此时我被困住了.任何建议/线索将非常感激.

提前致谢!

解决方法

问题是angular总是使用$http服务进行ASYNCHRONOUS调用(并且您无法更改该行为).由于页面在$http服务有机会发出请求之前退出,因此无法获得所需的结果.

如果您想在不使用任何第三方库的情况下使用workarround,请尝试以下代码

var onBeforeUnload = function () {

    var data = angular.toJson($scope.id...);//make sure you $scope is legal here...
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST","apiURL/unlock",false);//the false is for making the call synchronous
    xmlhttp.setRequestHeader("Content-type","application/json");
    xmlhttp.setRequestHeader("Authorization",token);
    xmlhttp.send(data);
}

它将阻止UI直到请求完成,因此尝试使服务器快速用户会注意到.

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...