从函数中获取返回值是d

Getting return value from function is d

本文关键字:返回值 获取 函数      更新时间:2023-09-26

我是使用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) {});

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

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

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) {});