【发布时间】:2014-06-26 17:11:27
【问题描述】:
我有一组自定义用户数据,我想对其进行 ajax 调用,如果没有用户数据,则进行另一个 ajax 调用以检索默认数据集,然后执行一个函数解析数据。这是一个例子:
var oData = [],
exampleUrl = 'example.php';
$.ajax({
url: exampleUrl + '?query=getUserData',
contentType: 'application/json;odata=verbose',
headers: {
'accept': 'application/json;odata=verbose'
},
success : function(data, request){
// Request succeeded
// Check the results
if(data.length){
// There are custom user results!
// Parse the results
oData = data;
}
else{
// There were no custom user results...
// Run another query to retrieve default values
$.ajax({
url: examplUrl + '?query=getDefaultData',
contentType: 'application/json;odata=verbose',
headers: {
'accept': 'application/json;odata=verbose'
},
success : function(data, request){
// Request succeeded
// Check the results
if(data.length){
// There was some default data!
// Parse the results
oData = data;
}
else{
// No data was found...
// Attempt to be helpful
console.log('No Default data was found!');
}
},
error : function(data, request){
// There was an error with the request
// Attempt to be helpful
console.log('Error retrieving data:');
console.log(data);
console.log(request);
}
});
}
},
error : function(data, request){
// There was an error with the request
// Attempt to be helpful
console.log('Error retrieving Custom User data:');
console.log(data);
console.log(request);
},
complete : function(){
// Do something with the data
index.displayData(oData);
}
});
问题在于,如果运行第二个 ajax 调用,则 oData 在传递给index.displayData() 时根本不包含任何数据。我猜这与 ajax 调用的异步性质有关,但不应该在 'success' 中的所有内容运行之后'complete' 运行?
我也知道我可能不应该使用 ajax“末日金字塔”,而应该使用 Promise,但我已经尝试过它们并一直得到相同的结果。
感谢您的帮助!
【问题讨论】:
-
您是否 100% 确定 data.length == 0?
-
你是对的..
complete绑定到 first ajax 调用。您在其中进行了单独的 ajax 调用,但这与第一个 ajax 调用是否实际完成无关。 IOWcomplete并不意味着“整个事情以及其中的一切都已执行”。但是.. 有什么理由不能只进行一次 AJAX 调用并更改服务器端逻辑以在未找到用户数据的情况下仅返回默认数据? -
@CrayonViolent 这是有道理的。不幸的是,我正在对 SharePoint 服务器进行 RESTful 调用,并且对服务器的响应方式没有太多控制。
-
好的,那么我会将您的“默认”逻辑移动到第一个 ajax 调用的完整和 eval
data中,然后从那里进行第二次调用(如果需要)。
标签: javascript ajax asynchronous jquery-deferred