2013-11-15 124 views
0

我有一個數組,其中包含Web服務的兩個URL。以下代碼正確執行這兩個帖子並將正確的數據輸出到屏幕。然而,有趣的是,該功能將只打印"2"到控制檯,但它正確地打印出對象的正確數目每個請求,屏幕保護蓋: enter image description here使用異步代碼的循環中的JavaScript關閉

你可以看到有不同數量從每個AJAX請求返回的對象。

$(document).ready(function() { 
      var urlList = ['../NewService.asmx/GetNames', '../NewService.asmx/GetPersons']; 
      //executes both functions 
      multipleAjaxCalls(urlList); 
      //ajax function definition 
      function multipleAjaxCalls(array) { 
       var functionArray = []; 
       for (var i = 0; i < array.length; i++) { 
        var func = (function() { 
         $.ajax({ 
          type: "POST", 
          url: array[i], 
          dataType: "json", 
          contentType: "application/json", 
          success: function (data) { 
           console.log('this is the index: ' + i); 
           console.log('ajax success ' + i); 
           console.log(data.d); 
          }, 
          error: function (xhr) { 
           console.log(xhr.status); 
          } 
         }) 
        })(i); //<--I honestly don't understand what passing paramters to these closing parens actually does 
          //in this case it doesn't affect the output 
        functionArray.push(func); 
       } 
       return functionArray //this is superfluous 
      } 
     }); 

爲什麼這個函數返回正確這兩組數據,但只打印出的"2"的指標,特別是當陣列具有兩個長度是多少?

+0

*「我真的不明白什麼傳遞參數給這些關閉的參數實際上「*您正在調用一個函數並將參數傳遞給它。想象一下你有一個函數'foo'。然後在'foo(i)'中,你調用'foo'並傳遞'i'作爲參數。這就是你在這裏做的。唯一不同的是,您沒有對該功能的引用,您正在定義並「在現場」調用該功能。它沒有任何意義,因爲如前所述,你沒有定義函數來期望*參數。 –

+0

@FelixKling英雄:) – wootscootinboogie

回答

0

修復

   function (yetanotherI) { 
        $.ajax({ 
         type: "POST", 
         url: array[yetanotherI], 
         dataType: "json", 
         contentType: "application/json", 
         success: function (data) { 
          console.log('this is the index: ' + yetanotherI); 
          console.log('ajax success ' + yetanotherI); 
          console.log(data.d); 
         }, 
         error: function (xhr) { 
          console.log(xhr.status); 
         } 
        }) 
       })(i) 

你正經過我的價值,anony功能,但不使用它。我改變了這一點。

這是如何工作的?內在功能沒有得到所謂的循環完成之前,所以當它被稱爲i(外一種)始終是2

+0

我沒有讀過它,但是這確實給了JS的單線程性質很多感......謝謝! – wootscootinboogie

+0

如果在循環結束前沒有調用內部函數,爲什麼'url:array [i]'指向數組中的正確索引..Ah !,因爲打印到屏幕上的索引i在回調函數中的成功屬性。 – wootscootinboogie

+0

@wootscootinboogie - 即刻得到評估,成功的東西只會在稍後評估。所以你的方式將爲'url'參數工作,但我認爲我已經使代碼更加清晰(並避免了將來的問題)。 – Hogan

0

你這樣做

(function(){ 
    // stuff 
})(something) 

你應該做這個

(function(something){ 
    // stuff 
})(something) 

否則,如果你創建一個封閉都不會有問題,你仍然不及格i它。

+0

兩次錯誤。他正在創建關閉,這是問題,他不想要第二個東西,他想要外部變量名稱。 – Hogan

+0

同樣的事情,我一直在概括他所遇到的問題。 – bevacqua