【问题标题】:Angular Ajax temporaly variablesAngular Ajax 临时变量
【发布时间】:2015-07-05 17:19:17
【问题描述】:

我正在尝试从 json 文件中获取 ajax 返回的记录数,但是当我尝试打印“.success 块”之外的记录数时,我没有得到在".成功块"

示例:

var total = 0;
$http.get("json/noticias.json")
  .success(function(response) {
    $scope.lista = response;
    total = response.noticias.length;
    alert(total);//Print 3
  });

alert(total);//Print 0

我还需要在第二张中打印 3。

【问题讨论】:

  • 哪个打印第一个 0 或 3?我猜是 0 对吧?
  • 您的要求是什么?

标签: javascript arrays ajax json angularjs


【解决方案1】:

这是因为$http.get() 是一个异步调用,这意味着执行流程不会停止$http.get() 获取所有值并执行.success() 函数内部的逻辑,然后移动到下一个事件序列。

$http() 调用获取数据并调用.success() 时,执行流程继续并执行下一条语句。因此,您首先在alert() 中得到0,然后是3。因此,在执行$http() 调用之外的alert() 时,total 的值仍然是0,因为total 尚未更新在.success() 回调中。

您应该使用 promises 和 $q 来处理 $http 调用的成功和错误条件。

【讨论】:

  • 好的,谢谢,尽管我已经在 .success() 中实现了目标,但我会尝试您的解决方案
【解决方案2】:

AngularJS 使用一个叫做 $q 的 promise 模块。所以你必须使用 then() 或 catch() 这样成功后会得到json数据

var total = 0;
 $http.get("json/noticias.json") .success(function(response) {
 $scope.lista = response;
 response.total = response.noticias.length; ;
 alert(total);//Print 3 
 }).then( 
function( response ) {
 alert(response.total); //print 3 
}); 

希望对你有帮助

【讨论】:

    【解决方案3】:

    您需要将长度分配给范围的total 属性,然后您可以在成功方法之外访问它并将其绑定到您的html元素。但请注意,一旦响应可用,您将能够访问 total 的更新值。以下应该可以解决您的问题:

    $scope.total = 0;
    $http.get("json/noticias.json")
      .success(function(response) {
        $scope.lista = response;
        $scope.total = response.noticias.length;
        alert($scope.total);//Print 3
      });
    
    alert($scope.total);//Print 0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-08
      相关资源
      最近更新 更多