將變量傳遞給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));
看起來像你正在遞歸。 –
當您從頂部的for循環調用RequestData()時,您不會傳遞'callback'參數。 – Barmar
你爲什麼從RequestData裏面調用'RequestData'? – Barmar