2015-05-24 63 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

相关问题