【发布时间】:2015-11-13 15:41:31
【问题描述】:
我对 javascript 很陌生,并试图弄清楚如何在发送到另一个函数的回调中将值添加到调用方数组。
基本代码为:
var newArray = new Array();
var oldArray = new Array();
oldArray.push(1);
oldArray.push(2);
oldArray.push(3)
for (var value in oldArray) {
someclass.functionThatWillPerformAjax(oldArray[value], function() {
// I am trying to figure out how to pass newArray in this callback
// so that when we receive the response from AJAX request,
// the value returned from the response pushed to a newArray
}
}
// once all calls are done, I have my newArray populated with values returned from server
【问题讨论】:
-
你不需要传递
newArray你可以通过闭包在回调函数中访问。 -
假设我的 someclass.functionThatWillPerformAjax() 存在于另一个文件中?
-
我想我们需要查看
someclass.functionThatWillPerformAjax的代码才能给你一个很好的指示。 -
我会说让你的“回调”函数包装在一个实际的 ajax 成功回调函数中,并将你的新数组传递给你当前调用回调函数的函数。
-
"once all calls are done" — 当所有 Ajax 请求 sent 时,该代码行将运行,not 当它们有 完成。
标签: javascript ajax callback