【问题标题】:Setting a Sammy.js session to the result of a JSONP request将 Sammy.js 会话设置为 JSONP 请求的结果
【发布时间】:2013-06-25 21:13:27
【问题描述】:

我的应用程序的一部分是使用来自 JSONP 请求的数据呈现的。我希望能够使用 Sammy.Session 在客户端缓存此请求的结果。

但是,我遇到了一些困难,因为 JSONP 请求是同步的。这是我当前的非工作代码:

this.get('#/projects', function(context) {
    var categories = this.session('categories', function() {
        var data;
        $.getJSON('http://mysite.com/projects/categories/?jsoncallback=?', null,
            function(json) {
                data = json.categories;
            });
            return data;
         });
    });

    // categories is undefined at this point,
    // because the JSONP call may not have finished

    // code that renders the data

    this.session('categories', categories);
});

如果类别在会话中,我希望 必须做的是发出 JSONP 请求。有没有办法让路由的其余代码等到 JSONP 请求完成?

【问题讨论】:

    标签: jquery jsonp sammy.js


    【解决方案1】:

    我能想到的解决此问题的唯一方法是,如果未找到会话,则不要尝试利用回调,并利用可从 JSON 请求的结果或会话可用的共享函数调用。如果有人知道更好的方法来实现这一点,我很乐意看到一个例子。

    this.get('#/projects', function(context) {
        ...
    
        var categories = this.session('categories');
    
        if (categories == undefined) {
            this.load('http://mydomain.com/projects/categories/?jsoncallback=?',
                {dataType: 'json'})
                .then(function(json) {
                    context.session('categories', json.categories);
                    // call to shared function
                });
        }
        else {
            // call to shared function
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2013-06-20
      • 1970-01-01
      • 1970-01-01
      • 2019-08-24
      • 2017-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多