JavaScript   发布时间:2022-04-16  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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",@R_801_11372@sE);//the @R_801_11372@se is for making the call synchronous
    xmlhttp.setrequestHeader("Content-type","application/json");
    xmlhttp.setrequestHeader("Authorization",token);
    xmlhttp.send(data);
}

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

大佬总结

以上是大佬教程为你收集整理的javascript – 如何在AngularJS中发送HTTP请求onbeforeunload?全部内容,希望文章能够帮你解决javascript – 如何在AngularJS中发送HTTP请求onbeforeunload?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。