我有一个for循环,它从子网站中的列表中获取数据,使用异步ajax请求在页面上构建一个html列表,这很有效,但我希望在生成列表后按顺序排列列表以按字母顺序显示列表订购。我正在使用javascript学习曲线,所以任何帮助表示赞赏。我需要在onWebsLoaded函数完成后运行sortProjects函数。
function onWebsLoaded(sender, args) {
for (var i = 0; i < this.webs.get_count(); i++)
{
client = "";
var title = this.webs.itemAt(i).get_title();
var desc = this.webs.itemAt(i).get_description();
var url = this.webs.itemAt(i).get_serverRelativeUrl();
id = (title).replace(/\ /g, "");
getProjectProperties(url, title, desc, client, id);
}
}
function sortProjects () {
tinysort('ul#projectstable>li');
}
function getProjectProperties (url, title, desc, client, id) {
$.ajax({
url: url + "/_api/web/lists/getbytitle('Project Properties')/items('1')",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
client = data.d.Title;
$('#projectstable').append("<li id='" + id + "' class='ms-ListItem'><a href='" + url + "'><span id='" + id + "Client' class='ms-ListItem-primaryText'>" + title + "</span><span class='ms-ListItem-secondaryText'>" + client + "</span><span class='ms-ListItem-tertiaryText'>" + desc + "</span></a></li>");
},
error: function () {
$('#projectstable').append("<li id='" + id + "' class='ms-ListItem'><a href='" + url + "'><span id='" + id + "Client' class='ms-ListItem-primaryText'>" + title + "</span><span class='ms-ListItem-secondaryText'>" + client + "</span><span class='ms-ListItem-tertiaryText'>" + desc + "</span></a></li>");
}
});
}
答案 0 :(得分:2)
您可以修改逻辑,以便存储从$.ajax()
调用返回的promise数组。然后,您可以apply()
将该数组发送到$.when
并致电sortProjects()
。试试这个:
function onWebsLoaded(sender, args) {
var requests = [];
for (var i = 0; i < this.webs.get_count(); i++) {
client = "";
var title = this.webs.itemAt(i).get_title();
var desc = this.webs.itemAt(i).get_description();
var url = this.webs.itemAt(i).get_serverRelativeUrl();
id = (title).replace(/\ /g, "");
requests.push(getProjectProperties(url, title, desc, client, id));
}
$.when.apply($, requests).done(sortProjects);
}
function sortProjects () {
tinysort('ul#projectstable>li');
}
function getProjectProperties (url, title, desc, client, id) {
// note 'return' below
return $.ajax({
url: url + "/_api/web/lists/getbytitle('Project Properties')/items('1')",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
client = data.d.Title;
$('#projectstable').append("<li id='" + id + "' class='ms-ListItem'><a href='" + url + "'><span id='" + id + "Client' class='ms-ListItem-primaryText'>" + title + "</span><span class='ms-ListItem-secondaryText'>" + client + "</span><span class='ms-ListItem-tertiaryText'>" + desc + "</span></a></li>");
},
error: function () {
$('#projectstable').append("<li id='" + id + "' class='ms-ListItem'><a href='" + url + "'><span id='" + id + "Client' class='ms-ListItem-primaryText'>" + title + "</span><span class='ms-ListItem-secondaryText'>" + client + "</span><span class='ms-ListItem-tertiaryText'>" + desc + "</span></a></li>");
}
});
}