从函数中获取返回值是d

时间:2015-12-22 13:02:32

标签: javascript

我是使用AngularJS和JavaScript的新手。返回值后,我得到了d。我正确地调用了这个函数吗?请在下面的代码中告诉我我做错了什么。提前致谢。 这是我的代码:

     function volunteerNumbr (ProspectID){var value1;

        console.log("volunteerNumbr[i].ProspectID",ProspectID)
        $http.get(baseURL + 'participant/prospectid/'+ProspectID).success(function(participantData, status, headers, config){

            var participantData=JSON.stringify(participantData);

            if(JSON.parse(participantData) == null){
                value1 =  -1;
                //console.log ("$rootScope.value1",$rootScope.value);
            }
            else{
               value1 = JSON.parse(participantData).length;
                console.log ("$rootScope.value2",$rootScope.value);

            }
        }).error(function(data, status, header, config) {
                console.log("not fecthed")
            });

         console.log ("$rootScope.value3",value1);
         return value1;
    }



    $http.get(baseURL + 'prospect/all/').success(function(data, status, headers, config) {
        $scope.prospects = data;    //show data on list


        var prospect=JSON.stringify($scope.prospects);
        var prospect=JSON.parse(prospect);

        var prospectLength = prospect.length;

        for(var i = 0; i < prospectLength; i++){

            prospect[i].num = volunteerNumbr(prospect[i].ProspectID);


        }
        console.log("all prospect",prospect);



    }).error(function(data, status, header, config) {});

1 个答案:

答案 0 :(得分:0)

$http.get()实际上会返回一个promise对象,而不是您在success()内返回的数据,

所以如果你需要在成功块中设置值prospect[i].num,如下所示 通过将$http.get括在 IIFE(立即调用函数表达式)中来创建函数,并将当前索引值传递给for循环,以便包含该ajax调用的索引值。 / p>

JS代码:

$http.get(baseURL + 'prospect/all/').success(function(data, status, headers, config) {
$scope.prospec = data;    //show data on list


var prospect=JSON.stringify($scope.prospec);
var prospect=JSON.parse(prospect);
//console.log("all prospect",prospect.length);
var prospectLength = prospect.length;

for(var i = 0; i < prospectLength; i++){

   // prospect[i].num  = volunteerNumbr(prospect[i].ProspectID);

      //Creating a IIFE and enclose the $http.get inside it
      (function (index) {
      $http.get(baseURL + 'participant/prospectid/'+prospect[i].ProspectID).success(function(participantData, status, headers, config){

        var participantData=JSON.stringify(participantData);
        if(JSON.parse(participantData) == null){
            prospect[index].num =-1;
             }
        else{
            prospect[i].num =JSON.parse(participantData).length;
                                }
    }).error(function(data, status, header, config) {
            console.log("error")
        });
     }(i));

     console.log("num",prospect[i].num);
      }
console.log("all prospect",prospect);
$scope.prospects= prospect;
console.log("all $scope.prospects",$scope.prospects);

}).error(function(data, status, header, config) {});