将变量传递给javascript回调函数时遇到问题。无法理解,为什么它不起作用。
这是代码。我通过变量' i'通过许多功能。 '功能1'只是一个例子,有一大段代码。
也是回调中的代码,' var tmpl'只是一个例子,不要注意这一点。问题是为什么我无法通过' i'变量
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) {
- 我得到未解决的类型或变量&#39;我&#39;&#39;错误,回调不起作用。否则,如果我没有通过&#39;我&#39;在回调中 - 我没有收到此错误,但看起来回调也不起作用,因为此回调代码无法正常工作RequestData(function (json) { alert('here!');}
- 我没有收到消息&# 39;这里&#39;,但没有错误。在这两种情况下,回调呼叫都是:callback(JSON.parse(xhr.responseText));
答案 0 :(得分:1)
首先,i
未定义,因为您正在调用RequestData(i, function())
,而i
未定义。
您只能从function1()
调用RequestData,但该方法永远不会执行,并且永远不会指定回调。
要使其有效,请从RequestData(i)
移除function1()
来电。然后将方法调用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();