[英]Access controller action variable in jquery and display it in ruby on rails
我是Jquery和Ajax的新手。...我想做的是..我有一個控制器操作,該操作讀取文件內容並將其存儲在變量中。 我想從jquery傳遞文件名,並希望通過jquery中的變量訪問該文件內容,並將其顯示在div標簽中。 為此,我在控制器中使用了此代碼...
requests_controller.rb
def download
IO.foreach "#{RAILS_ROOT}/Backend/History/#{params[:filename]}" do |line|
@file_content << line
@file_content << '<br/>'
end
end
jQuery中的代碼是...
jQuery("#play").click(function() {
jQuery.get("/requests/download_log", { filename: filename});
});
目前尚不清楚您要做什么。 您是否要在jquery視圖中訪問controller變量,還是要從ajax jquery函數請求控制器操作並從響應中獲取一些數據?
我認為您想做第一件事,因此可以在控制器上做:
class MyController < ApplicationController
def my_action
@file_content = some_content
end
end
在視圖my_action.html.erb上
<script type="text/javascript">
$(document).ready(function() {
$("#play").click(function() {
$.get("/requests/download_log", { filename: <%= j @file_content %> });
});
});
</script>
現在,如果有機會您想做我說的第二件事,您可以做
class MyController < ApplicationController
def download_log
@file_content = some_content
respond_to do |format|
format.json { render json: @file_content.to_json }
end
end
end
並在視圖上
success_handler = function(json_data) {
// Do any operation with the json_data
}
error_handler = function(jqXHR, textStatus, errorThrown) {
// Handle ajax errors here
}
$("#play").click(function() {
$.ajax("/requests/download_log.json", dataType: "json", success: success_handler, error: error_handler);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.