我需要一些帮助来响应 AJAX 调用。这是我想做的:
- 对我的 Rails 应用进行 AJAX 调用以获取 HTML 文档。
- 在 Rails Controller 中,从磁盘读取 HTML 文档。然后使用“render html:@htmldoc”将文档发送到 View
- 在 View 内部,我在 div 中有一个标签 ID“类(class)”。使用来自具有 HTML 文档的 AJAX 调用的响应,我将文档放入“类(class)”标签中。但是 HTML 被呈现为带有“类(class)”标签的 TEXTNODE,而我需要将它呈现为 HTML。
这是我在 new.html.erb 中的看法:
<div id="lesson">
<h2>Choose a lesson on the left panel to start your study module.</h2>
</div>
<div>
<button type="button" class="btn btn-primary"id="btn_next">Next</button>
</div>
这是我在 new.html.erb 中的 AJAX 调用:
$(document).ready(function(){
$("#btn_next").click(function(){
$.ajax({
type:'POST',
url:'/study',
data: { id: "demo.html" },
success:function(result){
$("#lesson").html(result);
}
});
});
});
这是我的路线.rb:
get '/study', to: 'study_sessions#new'
post '/study', to: 'study_sessions#create'
这是我在 Controller 中的代码:
def create
@filename = params[:id]
@htmldoc = File.read("public/uploads/#{@filename}") if File.exist("public/uploads/#{@filename}")
render html: @htmldoc
end
这是我的 demo.html 文件:
<table class="table table-striped">
<th>Head 1</th><th>Head 2</th>
<tr><td>Row 1</td><td>row 1</td></tr>
<tr><td>Row 2</td><td>row 2</td></tr>
</table>
这是我在单击按钮之前从浏览器查看的结果:
Choose a lesson on the left panel to start your study module.
这是我点击按钮后的结果:
<table class="table table-striped"> <th>Head 1</th><th>Head 2</th<tr><td>Row 1</td><td>row 1</td></tr> <tr><td>Row 2</td><td>row 2</td></tr> </table>
我希望 demo.html 文件将呈现为一个漂亮的 HTML 表格,而不是一串文本。
非常感谢所有帮助的人!
最佳答案
您需要使用 .html_safe
方法告诉 Rails 将其呈现为 html 内容。尝试这样做:
render html: @htmldoc.html_safe
关于html - rails : Render HTML directly from controller.,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38835262/