2015-06-26 22 views
1

Im由于某种原因而不得不使用此js代码。我无法访问ajax函数中的变量。 我试图通过将“格式化”变量放在ajax函数上面来解决这个问题,但是我无法从里面访问它。我该如何解决这个问题?为什么我无法访问在上范围中创建的变量

angular.module('ireg') 
.controller("compoundSearchController", function(){ 
    var vm = this; 
    vm.searchText = "Enter your search here..."; 
    vm.compounds = getJSON(); 

    function getJSON(){ 
     var formatted = "initial"; 

     console.log(formatted); // equals initial 

     $.ajax({url: "http://localhost:8080/ireg/app/php/returnAllCompounds.php", success: function(result){ 
      formatted = jQuery.parseJSON(result); 
      console.log(formatted); //equals the correct object 
     }}) 

     console.log(formatted); // equals initial 
     return formatted; 
    } 

    console.log(vm.compounds); // equals initial 

}); 

回答

1

AJAX调用的异步行为是实际行为和预期行为之间存在差异的原因。

更新您的代码以

var formatted = "initial"; 

$.ajax({url: "http://localhost:8080/ireg/app/php/returnAllCompounds.php", success: function(result){ 
    formatted = jQuery.parseJSON(result); 
    vm.compounds = formatted; 
}}) 
+0

(http://imgur.com/wLUbeqt)正如您在ajax函数之外可以看到的那样,变量仍然是初始值?您认为所提供的代码之外的东西是什么?我只在这里引用它。 –

+0

我们再次尝试在收到AJAX响应之前访问“格式化”。如果您移动ajax回调函数中的console.log,您将能够看到更新后的值,即来自第no行。 14号线12根据你的截图。 – nikhil

0

,因为它们在本质上asynchronous你不能得到外面success Ajax调用的响应。您需要使用他们的回拨来获得类似success的回拨,或者您也可以使用.then函数,该函数可在ajax呼叫得到解决时获得呼叫。

注意

不要说会搞乱了digest 周期,则需要手动强制它,不要用$http

更新替代AJAX AngularJS混合jQuery的AJAX

以下是角度版$.ajax

$http.get("http://localhost:8080/ireg/app/php/returnAllCompounds.php") 
    .success(function(result){ 
     formatted = jQuery.parseJSON(result); 
     console.log(formatted); //equals the correct object 
    }}); 
+0

@Chris Chevalier对你有帮助吗? –

相关问题