我试图写一个可以决定是否在localStorage的比不调用AJAX方法从服务器获取数据,否则就应该调用AJAX API,并将结果存在静态数据的代码在localstorage中,并将数据返回给它的调用方法。调用jQuery的AJAX功能的localStorage
这里是我的代码:
staticService = function (key) {
return $.ajax({
type: 'GET',
url: "xxxxx.ashx/" + key,
dataType: "json",
success: function(result){
store.save(key, result);
}
});
}
var getFromStore = function (key)
{
if (key) {
var result = store.fetch(key);
if (!result) {
staticService(key);
}
return result;
}
}
var staticdata = {
gender: [{value:"M",text:"Male"}, {value:"F",text:"Female"}],
maritalStatus: getFromStore('availableMaritalStatus')
};
问题:Ajax调用非同步,每当我经过那些不存储密钥它返回null,但它会在localStorage的Ajax调用和存储数据。我需要somthing像
{
check list from store if exists return the list otherwise call ajax, get the list, store it in localStorage and return to user but without blocking UI
}
我怎么能通过改变我的代码来实现这一点?最好的做法是什么?
编辑:如何更改staticdata变量的逻辑,使我得到staticdata.maritalStatus一个有效的数据,而不是空。我正在加载应用程序负载的静态数据。 如果我尝试调用getFromStore的次数,我不知道我什么时候会从服务器接收数据,因为这将调用多次susccess回调。我希望静态数据在所有静态服务成功返回数据时被调用。
的可能重复[?如何返回从AJAX调用的响应(http://stackoverflow.com/questions/14220321/how-to-return-the-response-from- an-ajax-call) –
您需要传递一个回调函数,该函数可以在获取关联值时运行,而不是在函数结尾处使用返回值。然后可以使用已存储的本地值调用回调,或者在完成时使用从ajax调用返回的值来调用回调。 – Archer
但回调中的问题是我不知道我收到的回应是哪个键。我必须一次性调用多个api服务。 –