2016-03-08 103 views
1

我有一個實例變量,我的Rails控制器中的@source_code想通過成功函數在我的Ajax響應中檢索。我從我的index.html.erb文件調用了這個Ajax函數,它呈現一個show.html.erb文件。我想讓我的文本區域打印出@ source_code.code的值。從Rails控制器讀取Rails控制器中的變量值

SourcesController.rb

def show 
    Rails.logger.debug("REACHED: show >>") 
    @source_code = Source.find_by(id: params[:id]) 
    Rails.logger.debug("REACHED: source_code >>" + @source_code.code.to_s) 
    @sources = Source.all 
end 

index.html.erb

function updateTextArea(source_id){ 
    console.log(source_id); 
    $.ajax({ 
    type: "GET", 
    url: "/sources/" + source_id, 
    data: {source_id: source_id}, 
    success: function (response){ 
     alert("Ajax success") 
     console.log("<%= @source_code %>"); 
     editor.session.setValue("<%= @source_code %>"); 
    }, 
    error: function(){ 
    alert("Ajax error!") 
    } 
}); 

回答

2

擴展在Nycen的答案,你首先要控制器處理Ajax請求並返回一個JSON響應:

def show 
    respond_to do |format| 
    format.json { render json: Source.find_by(id: params[:id]) } 
    end 
end 

PS:要注意這一點,它會發送所有來源記錄的字段的下降電線。我在模型上調用slice(請參閱ActiveRecord.slice())以限制JSON中返回的字段。

然後你JavaSript需要使用Ajax調用的JSON結果:

function updateTextArea(source_id){ 
    console.log(source_id); 
    $.ajax({ 
    type: "GET", 
    url: "/sources/" + source_id, 
    success: function (response){ 
     alert("Ajax success") 
     console.log(response.code); 
     editor.session.setValue(response.code); 
    }, 
    error: function(){ 
    alert("Ajax error!") 
    } 
}); 

這取決於你的路線是如何設置的,但應該沒有必要設置data財產Ajax調用。您的路線可能會將其從URL路徑中提取出來:/sources/12345

請注意,此設置沒有show.html.erb。沒有看法,你的控制器只返回JSON。

+0

非常感謝!這真的有助於進一步澄清Nycen的評論,這正是我期待的。 – A21

+0

太棒了,我無法在回答問題時輕鬆編寫代碼。我可能會將「響應」重命名爲「源」,以使其更加明確,但那只是我。 – Nycen

1

你期待你的成功處理程序能夠訪問@source_code就像一個 「show.html.erb」 視圖會,但它不會那樣工作。

當您使用ajax時,該方法從瀏覽器調用;它是您從服務器發送的一段代碼,它仍然可以與它交互,但它無法訪問控制器變量。

所以,你的show動作需要渲染你的處理器可以理解的東西,比如json。然後,通過閱讀您的「回覆」變量,您可以在成功時訪問它。