List1有一个List2的查阅列。我需要使用JSOM为两个列表添加列值。 目前我正在从List1中获取executeAsync调用中每个项目的列值...
var List1 = context.get_web().get_lists().getByTitle('List1');
var List2 = context.get_web().get_lists().getByTitle('List2');
var collListItem = List1.getItems(camlQuery);
context.load(collListItem);
context.executeQueryAsync(onQuerySucceeded, onQueryFailed);
function onQuerySucceeded(sender, args) {
var listItemEnumerator = collListItem.getEnumerator();
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
var listItemProject = oListItem.get_item('ProjectID'); // my lookup column
var listProjectLookupId = listItemProject.get_lookupId();
var itemProject = List2.getItemById(listProjectLookupId);
var country= null;
context.load(itemProject);
context.executeQueryAsync(function () {
country = itemProject.get_item('Country'); // columns from List2
});
// using column values from both lists
}
enter code here
但是在第二次异步调用中我得到的是空值......可能它们并没有一个接一个地发生..
答案 0 :(得分:2)
我建议你利用List Joins and Projections从父/子列表中检索数据。
假设以下列表:
Contacts
- 包含Country
查询字段(目标列表:Countries
)Countries
然后,以下示例演示了如何从两个列表中检索列表项。
示例强>
function createJoinQuery(joinListTitle,joinFieldName,projectedFields)
{
var queryText =
"<View>" +
"<Query/>" +
"<ProjectedFields>";
for(var idx in projectedFields) {
queryText += String.format("<Field Name='{0}_{1}' Type='Lookup' List='{0}' ShowField='{1}' />",joinListTitle,projectedFields[idx]);
}
queryText +=
"</ProjectedFields>" +
"<Joins>" +
"<Join Type='INNER' ListAlias='{0}'>" +
"<Eq>" +
"<FieldRef Name='{1}' RefType='Id'/>" +
"<FieldRef List='{0}' Name='ID'/>" +
"</Eq>" +
"</Join>" +
"</Joins>" +
"</View>";
var qry = new SP.CamlQuery();
qry.set_viewXml(String.format(queryText,joinListTitle,joinFieldName));
return qry;
}
function getListItems(listTitle,joinListTitle,joinFieldName,projectedFields,success,error)
{
var ctx = SP.ClientContext.get_current();
var web = ctx.get_web();
var list = web.get_lists().getByTitle(listTitle);
var items = list.getItems(createJoinQuery(joinListTitle,joinFieldName,projectedFields));
ctx.load(items);
ctx.executeQueryAsync(
function() {
success(items);
},
error
);
}
<强>用法强>
var listTitle = 'Contacts';
var joinListTitle = 'Countries'
var joinFieldName = 'Country';
var projectedFields = ['ID','Title'];
getListItems(listTitle,joinListTitle,joinFieldName,projectedFields,
function(items){
//print items
for(var i = 0; i < items.get_count(); i++){
var item = items.getItemAtIndex(i);
var contactName = item.get_item('Title');
var countryName = item.get_item('Countries_Title').get_lookupValue();
}
},
function(sender,args){
console.log(args.get_message());
});