2014-07-11 27 views
0

我正在函数(函数1)的成功处理程序中运行的循环中调用函数(函数2)。在循环的第一次迭代中,当我调用函数(函数2)时,函数被调用,并且在调用函数(函数2)的成功处理程序中指定执行操作。但在此之后,控制不会转移到第一个函数(Function1)的成功处理程序中的循环,并且循环不再执行。下面的代码说明了情况:调用函数(带成功处理程序)后执行循环停止

function Function1() 
{ 
    clientContext = SP.ClientContext.get_current(); 
    website = clientContext.get_web(); 
    var oList = web.get_lists().getByTitle('Test'); 
    var camlQuery = new SP.CamlQuery(); 
    this.collListItem = oList.getItems(camlQuery); 
    clientContext.load(this.collListItem, 'Include(ID, LinkFilename, Sender, Created, DocIcon)'); 
    clientContext.executeQueryAsync(
    Function.createDelegate(this, successHandler), 
    Function.createDelegate(this, errorHandler) 
    ); 

    function successHandler() { 
     var itemsCount = this.collListItem.get_count(); 
     for (i = 0; i < itemsCount; i++) { 
      var item = this.collListItem.itemAt(i); 
      alert(item.get_fieldValues()["Created"]); 
      Function2(); 
     } 
    alert('Loop ends'); 
    } 
    function errorHandler() { 
    } 
} 

现在功能2如下:

function Function2(){ 
    var context = SP.ClientContext.get_current(); 
    var web = context.get_web(); 
    var oList = web.get_lists().getByTitle('Test2'); 
    var camlQuery = new SP.CamlQuery(); 
    this.collListItem = oList.getItems(camlQuery); 
    context.load(this.collListItem, 'Include(ID, BaseName, Created, ServerUrl)'); 
    context.executeQueryAsync(
    Function.createDelegate(this, success), 
    Function.createDelegate(this, error) 
    ); 
    function success() { 
     var itemsCount = this.collListItem.get_count(); 
     for (i = 0; i < itemsCount; i++) { 
      var item = this.collListItem.itemAt(i); 
      alert(item.get_fieldValues()["ServerUrl"]); 
     } 
    } 
    function error(){ 
    } 
} 

现在我面临的问题是,代码只是循环的第一个第一次迭代运行函数,即使itemsCount大于1(在此之后,写入循环下面的代码(显示“循环结束”的警报)甚至不会执行)。 我无法发现错误,您的建议非常受欢迎。请通过这个指导我。

回答

0

这里有一些提示:

  1. 使用Chrome和开发者控制台(F12) - >网络选项卡,查看来自请求响应。
  2. 添加一些console.log语句来查看您的函数是否被调用,但并不总是成功回调。例如:
function Function2() { 
    console.log("Function2"); 
    var context = SP.ClientContext.get_current(); 
    var web = context.get_web(); 
    var oList = web.get_lists().getByTitle('Test2'); 
    var camlQuery = new SP.CamlQuery(); 
    this.collListItem = oList.getItems(camlQuery); 
    context.load(this.collListItem, 'Include(ID, BaseName, Created, ServerUrl)'); 
    context.executeQueryAsync(
     Function.createDelegate(this, success), 
     Function.createDelegate(this, error) 
); 

    function success() { 
     var itemsCount = this.collListItem.get_count(); 
     for (i = 0; i < itemsCount; i++) { 
      var item = this.collListItem.itemAt(i); 
      alert(item.get_fieldValues()["ServerUrl"]); 
     } 
    } 

    function error(sender, args) { 
     console.log("Request failed: " + args.get_message() + ". " + args.get_stackTrace()); 
    } 
} 

请确保您有开发工具开放,当您使用的console.log因为这些语句会引起IE错误与开发工具关闭。