我正在尝试创建一个具有ajax请求的递归函数。我试图从外部递归函数访问一个在ajax请求中处理的数组,它返回初始值。
我的代码看起来像
function retreiveData(testArgument)
{
$.ajax({
url:"testManipulate.php",
type: 'POST',
data: 'dataString',
datatype: 'json',
data: {field : queryData, start : testArgument},
success:function(jsonQuery)
{
$.ajax({
url: base_uri + path,
type:'POST',
data : jsonQuery,
success : function(terms){
var responseJson=JSON.parse(terms); // response JSON generated on download button click
for ( var g = 0; g < responseJson.hits.hits.length; g++) {
test[g] = (_generate_list(c, _field_select)); //function
if(test[g].length!==0){ //Leaving out blank entries
newTest[k]=test[g].join("; ") + "\n"; //separating each individual values with semi colon
k++;
}
}
if(testArgument < (4-1)*10)
{
retreiveData(testArgument+10);
}
i++
}
});
};
retreiveData(0);
alert(newTest.length);
警告newTest.length只会警告0,它不会给出最终值,即数组长度。可能有什么不对?
答案 0 :(得分:0)
这是因为你的ajax函数是异步的,你应该尝试使用回调函数:
function retreiveData(testArgument, callBack)
{
$.ajax({
url:"testManipulate.php",
type: 'POST',
data: 'dataString',
datatype: 'json',
data: {field : queryData, start : testArgument},
success:function(jsonQuery)
{
$.ajax({
url: base_uri + path,
type:'POST',
data : jsonQuery,
success : function(terms){
var responseJson=JSON.parse(terms); // response JSON generated on download button click
for ( var g = 0; g < responseJson.hits.hits.length; g++) {
test[g] = (_generate_list(c, _field_select)); //function
if(test[g].length!==0){ //Leaving out blank entries
newTest[k]=test[g].join("; ") + "\n"; //separating each individual values with semi colon
k++;
}
callBack(newTest);
}
if(testArgument < (4-1)*10)
{
retreiveData(testArgument+10);
}
i++
}
});
};
retreiveData(0, function(newTest){
alert(newTest.length);
});