2012-07-09 81 views
0

我想寫一些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

我的0.02:警報提供足夠的時間等待WS回答。檢查異步調用和回調的使用 – Alfabravo 2012-07-09 21:38:37

+0

瞭解異步調用如何工作,或將其設置爲同步模式並處理xD的後果 – TheZ 2012-07-09 21:41:24

回答

1

這可能是由於這個異步代碼

$().SPServices({ 
     operation: "GetList", 
     listName:  qs["list"], 
     completefunc: parseList 
}); 

警報暫時停止線程執行,足以使回調函數的調用

所以嘗試移動這部分

console.log(controls.length);   // this outputs 6 
for (var i=0; i<controls.length; i++) { 
    controls[i].addControl(); 
} 

分成parseList()功能

1

$().SPServices是一個異步功能。在調用parseList之前,controls陣列將不會被填充。移動循環以將控件添加到您的parseList回調中。

相關問題