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