【发布时间】:2013-03-21 04:01:37
【问题描述】:
我想使用localStorage 实现从服务器数据中检索的“缓存”。请求参数 (requestData) 将是唯一标识符。这是我的代码:
App = {};
App.Service = function(name) {
this.name = name;
};
App.Service.prototype.sendRequest = function(requestData) {
// process request data somehow and store to local variable
var identifier = $.param(requestData);
$.ajax({
url: 'web/api',
success: function(data) {
// can identifier differ from calculated before ajax call?
// for example if someone else start this method in the same time?
localStorage.setItem(identifier, data);
},
error: function(jqXHR, textStatus, errorThrown) {
// handle error
},
type: "POST",
data: requestData
});
};
这是我的问题:假设我已经多次启动了 sendRequest 方法。每个success 回调方法会在他自己的identifier 上运行还是它们会混合在一起(换句话说,错误的标识符将分配给响应数据)?
【问题讨论】:
-
您无需担心 ajax 调用之间的数据混乱,因为每个 sendRequest() 调用都会创建自己的本地“标识符”变量,该变量与成功/错误回调函数的闭包相关。
-
谢谢。我不知道(我什至没有想过)每个函数的调用都会创建它自己的地址空间:(
标签: javascript jquery ajax local-storage