[英]Execute Javascript only on page load, not PostBack (SharePoint)
[英]Sharepoint Javascript failing on page load
我正在尝试获取学校列表以放入select
元素的option
。 我希望在页面加载时添加下拉选项,但我没有做正确的事。 如果直接使用button
元素调用下面的代码,则该代码有效,但不适用于页面加载。
我得到的错误是var clientContext = new SP.ClientContext(siteUrl);
行上的“对象不支持此操作” 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
将等待'sp.js'文件完成加载,然后再调用retrieveListItems()
。 但是,如果未请求“ sp.js”,它将永远等待。 这就是为什么我们首先调用executeFunc
来请求“ sp.js”的原因。 但是,它并不能保证继续前进之前已加载它。 它只是将其添加到需要加载的脚本堆栈中,然后运行回调。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.