大佬教程收集整理的这篇文章主要介绍了javascript – 如何在AngularJS中发送HTTP请求onbeforeunload?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我的第一站是: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(没有服务),但这也没有用.此时我被困住了.任何建议/线索将非常感激.
提前致谢!
如果您想在不使用任何第三方库的情况下使用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); }
以上是大佬教程为你收集整理的javascript – 如何在AngularJS中发送HTTP请求onbeforeunload?全部内容,希望文章能够帮你解决javascript – 如何在AngularJS中发送HTTP请求onbeforeunload?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。