我有这个JS代码。我正在尝试在执行多个Ajax调用后达到dataJson
对象的总长度。当我单独尝试呼叫时,它们会返回正确的数字(60,64和5)。
当我使用when
组合调用时,我得到60,64和64作为计数。知道为什么会这样发生吗?我将不胜感激任何帮助。
var publicationData = new Array();
var researchers = [];
var year = [];
var title = [];
var pub = [];
var dataJson = [];
callServerAsync();
function callServerAsync(){
var p1 = $.get('Year2013.html').then(function(responseData) {
return handleData(responseData); //count returns 60
});
var p2 = $.get('Year2014.html').then(function(responseData) {
return handleData(responseData); //count returns 64
});
var p3 = $.get('tauchi_publications.html').then(function(responseData) {
return handleData(responseData); //count returns 5
});
return $.when(p1, p2, p3).then(function(result1, result2, result3){
//count returns 60, 64, 64
});
}
function handleData(responseData){
var htmlObject = document.createElement('div');
htmlObject.innerHTML = responseData;
pub = htmlObject.getElementsByClassName("julkaisu");
getPublicationData(pub);
getResearchersYearTitle(publicationData);
dataJson = createJson(researchers,year,title);
var count = Object.keys(dataJson).length;
console.log(count);
return dataJson;
}
function createJson(researchers,year,title){
var dataJson = [];
for(var i = 0; i < researchers.length; i++){
dataJson.push({ "Researchers": researchers[i],
"Year": year[i],
"Title": title[i]
});
}
return dataJson;
}