2013-03-26 65 views
0

我有一個控制器動作(讓我們稱之爲some_controller_action),需要渲染出一些json(用於提取javascript)和相同的使用some_controller_action.js.erb時間刷新/重新渲染一個部分。如何渲染json並同時使用AJAX刷新局部(Rails)

我的代碼的建議是這樣的:

def some_controller_action 

    # 
    # lots of code here 
    # 

    respond_to do |format| 
    render :json => {:something => something}, :status => :ok 
    format.html { 
     redirect_to somewhere 
    } 
    format.js 
    end 
end 

客戶端AJAX/JavaScript的觸發該動作,並且接收JSON作爲響應。它看起來像這樣:

someCoffeescripAction = -> 
    $.ajax 
    type: "post" 
    dataType: "json" 
    data: 
     some_data_name: some_data_content 
    url: "some_url/some_controller_action" 
    success: (data, status, xhr) -> 
     do_something_with_the_response(data) 

    error: (xhr, textStatus, errorThrown) -> 

當然,這不工作,因爲我不允許在同一個動作渲染兩次我。但那麼該怎麼辦?

回答

1

你的javascript看起來像什麼?你是否通過ajax獲取控制器動作?如果是這樣,那麼你只需要等到ajax調用完成,然後觸發重新渲染你的partial,或者通過使用剛剛提取的json數據,或者通過調用另一個ajax函數。

+0

嗨。是的,javasript中的AJAX獲取控制器操作。我已更新我的帖子以顯示此內容。 – ChristofferJoergensen 2013-03-27 14:42:11