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
});
(http://imgur.com/wLUbeqt)正如您在ajax函數之外可以看到的那樣,變量仍然是初始值?您認爲所提供的代碼之外的東西是什麼?我只在這裏引用它。 –
我們再次嘗試在收到AJAX響應之前訪問「格式化」。如果您移動ajax回調函數中的console.log,您將能夠看到更新後的值,即來自第no行。 14號線12根據你的截圖。 – nikhil