我试图得到一个学校列表放入option
select
元素。我希望在页面加载时添加下拉选项,但我没有做正确的事情。如果使用button
元素直接调用它,下面的代码可以工作,但它在页面加载时不起作用。
我得到的错误是“对象不支持此操作”行var clientContext = new SP.ClientContext(siteUrl);
var siteUrl= '/learning/schools';
window.load = init();
function init(){
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', retrieveListItems());
}
function retrieveListItems() {
var clientContext = new SP.ClientContext(siteUrl);
var oList = clientContext.get_web().get_lists().getByTitle('Schools');
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><Geq><FieldRef Name=\'ID\'/>' +
'<Value Type=\'Number\'>1</Value></Geq></Where></Query><RowLimit>10</RowLimit></View>');
this.collListItem = oList.getItems(camlQuery);
clientContext.load(collListItem);
clientContext.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded(sender, args) {
var listItemInfo = '';
var listItemEnumerator = collListItem.getEnumerator();
var schoolCodes = document.getElementById('classSchoolList');
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
var schoolOption = document.createElement('option');
schoolOption.value = oListItem.get_item('Title');
schoolOption.text = oListItem.get_item('Title') + " : " + oListItem.get_item('School');
schoolCodes.add(schoolOption);
}
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
你能试试吗?
//load the sp.js script and execute the init method
//no guarantee sp.js will be fully loaded before init() runs.
SP.SOD.executeFunc('sp.js', init());
function init(){
//ensure script is fully loaded, then execute retrieveListItems()
ExecuteOrDelayUntilScriptLoaded(retrieveListItems(), 'sp.js');
}
或者,
SP.SOD.executeFunc('sp.js', null, function(){
ExecuteOrDelayUntilScriptLoaded(retrieveListItems(), 'sp.js');
});
ExecuteOrDelayUntilScriptLoaded
将在调用retrieveListItems()
之前等待'sp.js'文件完成加载。但如果没有请求'sp.js',它将永远等待。这就是为什么我们首先要求executeFunc
请求'sp.js'。然而,在继续前进之前,它并未保证它已被加载。它只是将它添加到需要加载的脚本堆栈中,然后运行回调。