长话短说,我正在尝试将JSON返回AJAX中的相应数据值存储到这些全局数组中。我知道数组正在构建正确,因为我在AJAX中放置了警报,但当我把它放在AJAX之外时,数组仍未定义。
如何导出整个popData JSON对象以对其进行处理并将值存储在全局数组中,或者将AJAX中的数组填充到外部调用?我需要这些数组可以被另一个函数访问,以将人口值与用户选择的一小部分值进行比较 - 如果有人想建议一个更好的方法来做这个,但它必须拉动人口值onLoad,这是已在HTML中完成。我认为这是使用服务器上最少的AJAX调用来实现这一点的最简化的方法,但我愿意接受建议! :d
var popProducers = new Array();
var popProducersCount = new Array();
function getPopulationInfo(){
$.ajax({
url:phpURL,
cache:false,
dataType:"json",
data: { },
success:function(popData){
for (i=0;i<popData.length;i++){
//producers and producersCount should be the same length at all times!
//If current producer name isn't in array already
if(popProducers.indexOf(popData[i].ProducerName) == -1){
//add new element to represent new producer quantity (producerCount.length returns number of elements in the array, thus if there are no elements = 0 thus making index 0 equal to 1 and so on)
popProducersCount[popProducersCount.length] = 1;
//Adds the producer name to the list of producers
popProducers[popProducers.length] = popData[i].ProducerName;
} else {
//Otherwise, it will increment the index of the producersCount array corresponding with the pre-existing producer name's index by 1
popProducersCount[popProducers.indexOf(popData[i].ProducerName)] += 1;
}
}
}
});
alert("Population Data Alert: " + popProducers);
答案 0 :(得分:4)
.ajax()
及其内置的XMLHttpRequest()
创建 asyncronous 请求。这只是意味着,在alert()
处理程序之前遇到了success
语句。
此处为简单解决方案,将alert()
移到最底部的success
处理程序中。
如果您想以更合适的方式处理它,可以像
那样使用jQuerysDeferred
个对象
function getPopulationInfo(){
return $.ajax({
// lots of stuff
});
}
然后将其称为
getPopulationInfo().done(function() {
alert("Population Data Alert: " + popProducers);
});
通过返回.ajax()
方法,我们可以返回Deferred object
。简而言之,你可以为success
(。done()),error
(。fail())和complete
(.always())传递一些额外的回调