【发布时间】:2014-07-13 18:50:08
【问题描述】:
您好,我有以下问题 - 在循环中我有一定数量的 jQuery ajax 调用 - 在 ajax 调用的返回中,我想使用局部变量以及 ajax 调用返回的数据:
在 JavaScript 类 DOCache.class.js 中(注意我这里使用了全局变量 doCache,它也没有“感觉干净”但我不知道如何传递“this”):
function DOCache() {
this.cache = new Array();
this.capi = new JsonAPI();
// loads all the properties saved in the cache object
this.loadUpdateCache = function(allLoaded) {
for(var prop in this.cache) {
// a delay will be here for each object!
this.capi.get(this.cache[prop]['url'],(function(data) {
doCache.cache[prop]['data'] = data;
doCache.cache[prop]['ready'] = true;
if(doCache.cache[prop]['loaded'] instanceof Function) {
var propLoaded = doCache.cache[prop]['loaded'];
propLoaded(data);
}
// check all initialized
if(doCache.checkAllReady()===true && allLoaded instanceof Function) {
allLoaded(doCache.cache);
}
}) (prop) // KEY: If we have this, we get the correct prop - if removed, we get the correct data - but never both
);
}
};
}
在 JsonAPI.class.js 中:
function JsonAPI(){
this.ajax = function(request_method,api_url,data,done,fail,always) {
var jqxhr = $.ajax(
{
type:request_method,
dataType: "json",
url: JSON_BASE+api_url,
data: data
},JSON_BASE+api_url,data)
.done(function(data) {
if(done instanceof Function) {
done(data);
}
})
.fail(function(data) {
if(fail instanceof Function) {
fail(data);
}
})
.always(function(data) {
if(always instanceof Function) {
always(data);
}
});
return jqxhr;
};
this.get = function(api_url,done,fail,always) {
return this.ajax('GET',api_url,"",done,fail,always);
};
}
问题是我不知道如何在不使用 (prop) 显式传递的情况下将循环中的局部变量(每次循环迭代中的不同字符串)传递给实际的回调函数。但是如果我这样做,我不会从传入的回调中获取数据。
所以实际的问题是:如何在 Ajax 回调函数中使用迭代中的局部变量(显然在返回任何 ajax 响应之前结束)?
【问题讨论】:
-
可以将本地数据添加到
beforeSend中的jQueryjqXHR对象,并通过在done回调中添加附加参数在done中检索它
标签: javascript jquery ajax parameter-passing scope