【问题标题】:How to make angularjs $http POST call when user refresh a page?用户刷新页面时如何进行 angularjs $http POST 调用?
【发布时间】:2014-03-21 11:46:05
【问题描述】:

控制器:

app.run(function ($rootScope, $templateCache) {
    $rootScope.$on('$viewContentLoaded', function ($scope, $http) {     
        $templateCache.removeAll();
        alert("refresh.....");
        $http({
            url: '/angularjs-restful/check/check-session',
            method: "POST",
            data: {},
            isArray: false
        }).success(function(data, status, headers, config){
            alert("success.....");
            console.log('status: ' + status);
            console.log('data: ' + data);
        }).error(function(data, status, headers, config){
            alert('error');
        });        
        alert("end.....");
    });       
});

当用户按键盘上的 f5 或用鼠标手动刷新页面时,我需要进行 AJAX 调用。我怎样才能做到这一点? url 是一个返回 true 或 false 的休息服务。

【问题讨论】:

    标签: javascript angularjs http rootscope


    【解决方案1】:

    您可以使用window.onbeforeunload 函数来监听应在 f5 上触发的卸载事件。

    function ctrl($scope, $window) {
        angular.element($window).bind('beforeunload', function() {
            console.log('do ajax call');
        });
    }
    

    【讨论】:

    • 我建议使用$window 服务绑定到beforeunload 事件,以防您需要通过模拟测试您的AJAX 调用。示例:jsfiddle.net/LkPJX
    • 我试过了,还是不行。如何将您的代码添加到我上面发布的代码中?当我刷新页面时,警报(“刷新.....”)工作正常,在警报之后,我需要使用 $http 进行 ajax 调用来调用服务......我添加了您提供的代码“angular.element($window).bind('beforeunload', function() { console.log('do ajax call'); });”但警报完成后它不会运行
    猜你喜欢
    • 2011-09-23
    • 1970-01-01
    • 2016-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-12
    • 1970-01-01
    相关资源
    最近更新 更多