我的 Rails Controller 中有一个实例变量 @source_code,我想通过成功函数在我的 Ajax 响应中检索它。我从我的 index.html.erb 文件调用这个 Ajax 函数,它呈现一个 show.html.erb 文件。我想让我的文本区域打印出 @source_code.code 值。
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!")
}
});
最佳答案
扩展 Nycen 的回答,您首先希望您的 Controller 处理 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!")
}
});
这取决于您的路由是如何设置的,但是应该不需要在 Ajax 调用中设置 data
属性。您的路由很可能会从 URL 路径中提取它:/sources/12345
。
请注意,此设置中没有 show.html.erb
。没有 View ,您的 Controller 只返回 JSON。
关于javascript - 在 Rails View 中从 Rails Controller 读取变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35879235/