我想通过使用localStorage
来实现从服务器数据检索“缓存”。请求参数(requestData
)将成为唯一标识符。这里是我的代码:保存javasctipt中的ajax调用之间的状态
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()调用都会创建自己的本地'标识符'变量,这个变量绑定到成功/错误回调函数的闭包。 – accme 2013-03-20 20:15:22
谢谢。我不知道(我甚至没有想过),每个函数的调用创建它自己的地址空间:( – 2013-03-20 20:35:10