来自angular.element(document).ready或initController的$ .getJSON调用

时间:2015-06-06 11:18:00

标签: javascript angularjs

我正在使用以下代码段从服务器获取数据以加载页面的初始内容。

(function () {
'use strict';

angular
    .module('app')
    .controller('MyController', MyController);

MyController.$inject = ['UserService', '$rootScope', '$scope', '$cookieStore', 'AuthenticationService'];
function MyController(UserService, $rootScope, $scope, $cookieStore, AuthenticationService) {


    /*Discussion Board related Functions*/ 
    angular.element(document).ready(function () {
        // Get Current User
        $rootScope.globals = $cookieStore.get('globals') || {};
        $scope.currentUser = AuthenticationService.GetAuthData($rootScope.globals.currentUser.authdata);

        $.getJSON(
        "http://localhost/getSomeServerData.php",               
        { userName: $scope.currentUser },   
        $scope.getSomeDataResponse                                      
        );
    });

    $scope.getSomeDataResponse = function (jason) {
        var servRet = jason;
        alert("On Load Called-2");
    };
}

})();

但是,没有调用响应函数$ scope.getSomeDataResponse。

请让我知道这种方法有什么问题。

2 个答案:

答案 0 :(得分:3)

  

但是,响应函数$ scope.getSomeDataResponse不是   被叫。

     

请让我知道这种方法有什么问题。

问题是,您在声明之前引用了getSomeDataResponse。此外,您正在使用 jQuery getJSON() angularJS 代码中使用HTTP GET请求从服务器获取数据。

这不是特别推荐的做法。如果在页面中包含jQuery,当在指令中包装元素时,AngularJS将使用jQuery而不是jqLit​​e,否则它可以委托给jqLit​​e(这可能在所有情况下都不起作用)。为了更安全,请使用angular $http.get()服务而不是$.getJSON()

$http.get("http://localhost/getSomeServerData.php",{ userName: $scope.currentUser})
     .then(function(jason){
           //success handler function
           var servRet = jason;
           alert("On Load Called-2");
           },function(err){
             //error handler function
             alert(err);
          })

当然,您需要在控制器中注入$http服务才能使其正常运行。看看this线程,了解其他可能的替代方案。

干杯!

答案 1 :(得分:1)

首先,您必须在使用前定义结果函数。 其次,你必须正确使用$ .getJSON。所以这在修好后对我有用了

    $scope.getSomeDataResponse = function (jason) {
        var servRet = jason;
        alert("On Load Called-2");
    };

/*Discussion Board related Functions*/ 
    angular.element(document).ready(function () {
        // Get Current User
        $rootScope.globals = $cookieStore.get('globals') || {};
        $scope.currentUser = AuthenticationService.GetAuthData($rootScope.globals.currentUser.authdata);

        $.getJSON(
        "http://localhost/getSomeServerData.php",               
        { userName: $scope.currentUser }

        ).always($scope.getSomeDataResponse);

回调方法在jQuery中有所不同。通过查看jQuery文档来使用fail和done回调 http://api.jquery.com/jquery.getjson/

相关问题