[英]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.