出于某些原因,我正在努力使用这段js代码。我不能访问ajax函数中的变量。我试图通过将"formatted“变量放在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
});发布于 2015-06-27 04:18:01
AJAX调用的异步行为是造成实际行为与预期行为不同的原因。
将您的代码更新为
var formatted = "initial";
$.ajax({url: "http://localhost:8080/ireg/app/php/returnAllCompounds.php", success: function(result){
formatted = jQuery.parseJSON( result );
vm.compounds = formatted;
}})发布于 2015-06-27 04:18:04
因为它们本质上是asynchronous,所以在它的success之外无法获得ajax调用的响应。您需要使用它们的回调来获得类似于success的调用,或者您也可以使用.then函数,该函数在ajax调用得到解决时得到调用。
笔记
不要将jQuery ajax和AngularJS混用,这会扰乱
digest周期,您需要手动强制执行,一定要用$http替换ajax
更新
下面是angular版本的$.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
}});https://stackoverflow.com/questions/31081394
复制相似问题