[英]Rails: Render HTML directly from controller.
我需要一些幫助來處理 AJAX 調用的響應。 這是我想要做的:
這是我在 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);
}
});
});
});
這是我的routes.rb:
get '/study', to: 'study_sessions#new'
post '/study', to: 'study_sessions#create'
這是我在控制器中的代碼:
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 表格,而不是一串文本。
非常感謝所有幫助的人!
您需要告訴 rails 使用.html_safe
方法將其呈現為 html 內容。 嘗試這樣做:
render html: @htmldoc.html_safe
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.