我有一个if语句的函数,它包含两个独立的AJAX调用操作。基于名为subjectType的变量,调用的条件发生变化。如果我想获取用户信息,我需要给它userLoginName。如果我想获取网站信息,我需要给它webURL。
我可以使用if语句来完成此操作但是有没有更好的方法来执行此操作而不必重复大多数行?
var subjectType = if(/*I'll check the value of the drop down to see if a user or site report was asked for*/)?"GetGroupCollectionFromUser":"GetGroupCollectionFromWeb";
function parseSubjectColFromUser(subject){
var subjectGroups = [];
if (subjectType){
$().SPServices({
operation: "GetGroupCollectionFromUser",
userLoginName: subject,
completefunc: function(xData, Status){
$(xData.responseXML).find("Group").each(function(){
subjectGroups.push($(this).attr('Name'));
});
}
});
}else{
$().SPServices({
operation: "GetGroupCollectionFromWeb",
webURL: subject,
completefunc: function(xData, Status){
$(xData.responseXML).find("Group").each(function(){
subjectGroups.push($(this).attr('Name'));
});
}
});
}
return subjectGroups;
}
答案 0 :(得分:3)
应该很简单......我还假设你想在这里使用回调函数,因为你是通过AJAX请求这样做的。
function parseSubjectColFromUser(subject, myCallback){
var subjectGroups = [];
var params = {
operation: subjectType ? "GetGroupCollectionFromUser" : "GetGroupCollectionFromWeb",
completefunc: function(xData, Status){
$(xData.responseXML).find("Group").each(function(){
subjectGroups.push($(this).attr('Name'));
});
myCallback(subjectGroups);
}
};
if (subjectType) {
params.userLoginName = subject;
} else {
params.webURL = subject;
}
$().SPServices(params);
}