2015-05-24 65 views
-2

將變量傳遞給JavaScript回調函數時遇到問題。無法理解,爲什麼它不起作用。將變量傳遞給javascript回調函數

這是代碼。我通過許多函數傳遞變量'i'。 'function1'只是一個例子,有一大段代碼。

也是回調中的代碼,'var tmpl'只是一個例子,不重視那個。問題是爲什麼我不能通過'我'變量。

function function1() { 
    for (var i = 0; i < 10; i++){ 
     RequestData(i); 
    } 
} 
function RequestData(i, callback){ 
    var xhr = new XMLHttpRequest(); 

    xhr.open('GET', '/getitemID='+i, true); 

    xhr.send(); 

    xhr.onreadystatechange = function() { // (3) 
     if (xhr.readyState != 4) return; 
     if (xhr.status != 200) { 
      alert(xhr.status + ': ' + xhr.statusText); 
     } else { 
      alert(xhr.responseText); 
      callback(JSON.parse(xhr.responseText)); 
     } 
     xhr.close(); 
    } 
} 

RequestData(i, function (json) { 
    alert('here!'); 

    var tmpl = [ 
     '<div id="content"><div id="bodyContent">', 
     '<button onclick="RequestData("+i+")">Load Data!</button></div>', 
     '<div>#here!</div>' 
    ].join(''); 

    var body = document.querySelector('body'); 
    alert(body); 

    for (var i = 0; i < json.length; i++) { 
     var html = tmpl.replace('#here!', json[i].itemid); 
     body.insertAdjacentHTML('afterbegin', html); 
    } 
}); 

,如果我嘗試調用回調函數是這樣的:function RequestData(i, callback) { - 我得到「未解決的類型或變量‘我’」的錯誤,而回調不工作。否則,如果我不通過'我'在回調 - 我不會得到這個錯誤,但看起來像回調不起作用,因爲這個回調代碼不起作用RequestData(function (json) { alert('here!');} - 我沒有收到'這裏' ,但沒有錯誤。在兩種情況下,回撥呼叫爲:callback(JSON.parse(xhr.responseText));

+1

看起來像你正在遞歸。 –

+1

當您從頂部的for循環調用RequestData()時,您不會傳遞'callback'參數。 – Barmar

+1

你爲什麼從RequestData裏面調用'RequestData'? – Barmar

回答

1

首先,i未定義,因爲您致電RequestData(i, function()),而i未定義。

您只能從function1()調用RequestData,但該方法永遠不會執行,並且永遠不會指定回調。

要使其工作,請從function1()刪除RequestData(i)呼叫。然後將方法調用RequestData(i, function (json) {放在for循環中。最後致電function1(),你會得到你的結果。 (儘管沒有乾淨的代碼)。

function function1() { 
    for (var i = 0; i < 10; i++){ 
     RequestData(i, function (json) { 
      alert('here!'); 

      var tmpl = [ 
       '<div id="content"><div id="bodyContent">', 
       '<button onclick="RequestData("+i+")">Load Data!</button></div>', 
       '<div>#here!</div>' 
      ].join(''); 

      var body = document.querySelector('body'); 
      alert(body); 

      for (var i = 0; i < json.length; i++) { 
       var html = tmpl.replace('#here!', json[i].itemid); 
       body.insertAdjacentHTML('afterbegin', html); 
      } 
     }); 
    } 
} 
function RequestData(i, callback){ 
    var xhr = new XMLHttpRequest(); 

    xhr.open('GET', '/getitemID='+i, true); 

    xhr.send(); 

    xhr.onreadystatechange = function() { // (3) 
     if (xhr.readyState != 4) return; 
     if (xhr.status != 200) { 
      alert(xhr.status + ': ' + xhr.statusText); 
     } else { 
      alert(xhr.responseText); 
      callback(JSON.parse(xhr.responseText)); 
     } 
     //xhr.close(); // this is not an existing function 
    } 
} 

// run the for loop by calling this method 
function1(); 
+0

oh和xhr.close()不是一個函數。 – Sanders

相關問題