[英]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.