2011-12-13 30 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'需要回調。 –