2015-06-26 21 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對你有幫助嗎? –

相關問題