如果staticstorage中不存在静态数据,则调用jquery ajax函数

时间:2013-10-30 12:20:17

标签: javascript jquery ajax asynchronous local-storage

我正在尝试编写一个代码,该代码可以确定localstorage中是否存在静态数据,而不是调用ajax方法从服务器获取数据,否则它应该调用ajax api并将结果存储在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,但它会进行ajax调用并将数据存储在localStorage中。我需要像

这样的东西
{
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有效数据而不是null。我正在加载应用程序负载的静态数据。 如果我尝试多次调用getFromStore,我不知道何时将从服务器收回数据,因为这将调用大量的success回调。我希望在所有静态服务成功返回数据时调用静态数据。

1 个答案:

答案 0 :(得分:0)

result为null,因为您无法从异步ajax查询返回数据。 最好的方法是在查询是“成功”时执行回调函数并在arg中传递返回值。 那样:

staticService = function (key) {
       return $.ajax({
            type: 'GET',
            url: "xxxxx.ashx/" + key,
            dataType: "json",
            success: function(data) {
               store.save(key, data);
               callbackFunction(data); // Here you can call a callback function that will use your return value
            }
        });
}