我正在尝试使用ajax调用来调用同步调用来获取数据。
这是我的Jquery代码:
var baseurl = _spPageContextInfo.webServerRelativeUrl;
console.log(baseurl);
var ItemCount = $.Deferred();
function tilesCount(tilename, count)
{
var url = baseurl + "/_api/web/lists/getByTitle('policies')/rootFolder/Folders?$expand=ListItemAllFields";
count = 0;
$.ajax({
url: url,
dataType: 'json',
success: function(data) {
$(data.value).each(function (i, folder) {
count = count + 1;
});
console.log("Call 1: " + count)
ItemCount.resolve(count);
return count;
},
error: function(error){
console.log("Error: " + JSON.stringify(error));
ItemCount.reject;
}
});
}
$(document).ready(function () {
var count = tilesCount("");
$.when(count).then(function(data){
console.log("Call 2: " + data);
});
});
输出:
拨打1:1
调用2:未定义
同步调用工作正常,但我将数据视为未定义
答案 0 :(得分:1)
由于ajax是异步的return count;
将是空的
var count = tilesCount("");
所以最好的解决方案就是在你的方法中传递一个回调函数,只要你的ajax完成就可以调用它。
function tilesCount(tilename, count, callback)
将其包含在回调函数中
function(count) {
$.when(count).then(function(data){
console.log("Call 2: " + data);
});
}
所以你的$(document).ready
就是这样,只需在回调中添加参数count
$(document).ready(function () {
tilesCount("", "", function(count) {
$.when(count).then(function(data){
console.log("Call 2: " + data);
});
});
});
你的javascript代码现在就像这样
var baseurl = _spPageContextInfo.webServerRelativeUrl;
console.log(baseurl);
var ItemCount = $.Deferred();
function tilesCount(tilename, count, callback)
{
var url = baseurl + "/_api/web/lists/getByTitle('policies')/rootFolder/Folders?$expand=ListItemAllFields";
count = 0;
$.ajax({
url: url,
dataType: 'json',
success: function(data) {
$(data.value).each(function (i, folder) {
count = count + 1;
});
console.log("Call 1: " + count)
ItemCount.resolve(count);
return callback(count);
},
error: function(error){
console.log("Error: " + JSON.stringify(error));
ItemCount.reject;
}
});
}
$(document).ready(function () {
tilesCount("", "", function(count) {
$.when(count).then(function(data){
console.log("Call 2: " + data);
});
});
});