我想寫一些JavaScript,基於來自Sharepoint WebServices getList的響應構建html控件。我將控件存儲在一個數組中。在構建數組之後,長度爲0,直到我執行警報,然後它變成正確的數字。JavaScript的array.length是0,直到我做了一個警報()
var controls = [];
$(document).ready(function() {
// Make call to WebServices to retrieve list data
$().SPServices({
operation: "GetList",
listName: qs["list"],
completefunc: parseList
});
console.log(controls.length); // this outputs 0
alert("This has to be here to work."); // this has to be here, no idea why
console.log(controls.length); // this outputs 6
for (var i=0; i<controls.length; i++) {
controls[i].addControl();
}
});
function parseList(xData,status) {
$(xData.responseXML).find("Field").each(function() {
if ($(this).attr("ID") && $(this).attr("SourceID") != "http://schemas.microsoft.com/sharepoint/v3") {
if ($(this).attr("Type") == "Text") {
controls.push(new Textbox(this));
} else if ($(this).attr("Type") == "Choice" && $(this).attr("Format") == "Dropdown") {
controls.push(new Dropdown(this));
} else if ($(this).attr("Type") == "Choice" && $(this).attr("Format") == "RadioButtons") {
controls.push(new RadioButtons(this));
} else if ($(this).attr("Type") == "MultiChoice") {
controls.push(new MultiChoice(this));
} else if ($(this).attr("Type") == "Boolean") {
controls.push(new Boolean(this));
}
}
});
}
Alert似乎是唯一使controls.length
正常工作的東西。我只能認爲這是某種範圍的問題。任何見解都會被讚賞。
我的0.02:警報提供足夠的時間等待WS回答。檢查異步調用和回調的使用 – Alfabravo 2012-07-09 21:38:37
瞭解異步調用如何工作,或將其設置爲同步模式並處理xD的後果 – TheZ 2012-07-09 21:41:24