我试图编写一组可重用的函数来抽象一堆SharePoint的REST API Web服务,这可能是不必要的上下文,但我总觉得这些问题有点奇怪。
反正。端点都采用参数,我决定提供执行AJAX调用的操作并处理返回Javascript对象(如果有更好的方法来做到这一点,我还在学习,完全开放的建议)称为"选项"具有参数的属性,如:
ApiHelper.prototype.getListData = function(options){
//Set the base endpoint Url.
var executeUrl = "/web/lists/getByTitle('"+options.list+"')";
//Determine if the URI will have parameters.
var params;
var paramList = [];
if(options.select.length || options.filter.length || options.expand.length || options.top.length){
params = true;
paramList.push(options.select,options.filter,options.expand,options.top);
}else{
params = false;
}
//The first two ops are super basic and don't take parameters, so I collapse them into a single line.
if(options.op == 'All'){return this.execute(executeUrl).then(function(data){if(data.d){return data.d;}else{throw "Something bad happened..."}});
}else if(options.op == 'Id'){executeUrl+='/Id';return this.execute(executeUrl).then(function(data){if(data.d){return data.d.Id;}else{throw "Something bad happened..."}});
}else if(options.op == 'Forms' || options.op == 'Views' || options.op == 'WorkflowAssociations'){
executeUrl+=options.op;
return this.execute(executeUrl).then(function(data){
if(data.d && data.d.results){
return new QueryResults(data.d.results);
} else {
throw "Something bad happened...";
}
});
}else{
if(params){
//No idea...
}else{
//If we're doing Items but without params...
executeUrl+='/items';
}
return this.execute(executeUrl).then(function(data){
if(data.d && data.d.results){
return new QueryResults(data.d.results);
} else {
throw "Something bad happened...";
}
});
}
为了方便用户使用,我想让参数可选。最初,我使用参数做了类似的事情:
if(typeof options.select === 'undefined'){options.select = '';}
if(typeof options.filter === 'undefined'){options.filter = '';}
if(typeof options.expand === 'undefined'){options.expand = '';}
if(typeof options.top === 'undefined'){options.top = '10000';}
然后构建带有附加参数的URL,只需清空。那......工作,但它似乎不优雅,你知道,对于SharePoint,我永远无法确定它是否会起作用。所以,我的目标是查看选项对象,例如,如果有一个select语句,然后追加$ select = [whatever],但如果没有,那就不要了。过滤,展开和顶部相同。
答案 0 :(得分:1)
function getProps(obj){
var str='';
for(var prop in obj){
if(str)str+='&';
else str='?';
str+=prop+'='+obj[prop];
}
return str;
}
我希望这会有所帮助。
答案 1 :(得分:1)