2011-12-13 59 views
0

我使用前端框架并希望呈现页面。为此,我使用一个初始化函数来调用一个执行$ .ajax调用到后端的函数。但是,尽管在chrome dev工具中,请求是成功的,但每次我使用console.log时,它都会返回undefined。后端发送正确的结果,但未显示。

initialize: => 
    @build_recent() 
    @[email protected]_data 
    console.log(@payload) 

    render: => 
    $(@el).append homeTemplate(@payload) 
    @ 

    build_recent: => 
    $.ajax(
     url: '/build_recent' 
     dataType: 'text/json' 
     type: 'GET' 
     success: (data) => 
     @recent_data = data 
    ) 

更新:

简单地只使用render()不使用intialize和其他功能,我终于解决了这个问题是这样的:

render: => 
    $.ajax(
     url: '/build_recent/' 
     dataType: 'json' 
     type: 'GET' 
     success: (data) => 
     @payload = data 
     $(@el).append homeTemplate(@payload) 
     return @ 
    ) 

事实证明,问题是只有这dataType: 'json'先前我使用dataType: 'text/json'

现在它工作正常

回答

3

你的CoffeeScript呈现到:

var _this = this; 

({ 
    initialize: function() { 
    _this.build_recent(); 
    _this.payload = _this.recent_data; 
    return console.log(_this.payload); 
    }, 
    render: function() { 
    $(_this.el).append(homeTemplate(_this.payload)); 
    return _this; 
    }, 
    build_recent: function() { 
    return $.ajax({ 
     url: '/build_recent', 
     dataType: 'text/json', 
     type: 'GET', 
     success: function(data) { 
     return _this.recent_data = data; 
     } 
    }); 
    } 
}); 

而且你不能从一个Ajax声明回报。你必须使用回调!

所以您呈现JS代码可以改为:

({ 
    initialize: function() { 
    _this.build_recent(); 
    //moved into callback 
    }, 
    render: function() { 
    $(_this.el).append(homeTemplate(_this.payload)); 
    return _this; 
    }, 
    build_recent: function() { 
    return $.ajax({ 
     url: '/build_recent', 
     dataType: 'text/json', 
     type: 'GET', 
     success: function(data) { 
     _this.recent_data = data; 
     //in callback 
     _this.payload = _this.recent_data; 
     console.log(_this.payload); 
     //prob want to render: 
     _this.render(); 
     } 
    }); 
    } 
}); 
+1

实际上,如果你设置在AJAX异步选项= FALSE您可以管理直接返回一个值(但它会冻结页面,所以我不会告发不推荐它) – Guillaume86

+0

@ Guillaume86我不想推荐大声笑 – Neal

+0

对,这是一个异步问题。如果你希望'build_recent'只是进行Ajax调用,并且你想在调用之后做一些事情,那么'build_recent'需要回调。 –