我想使用 link_to
调用名为 show 的 Controller 操作。发生这种情况,我收到一条 200 消息。现在我想用返回的内容更新 div
。
Controller 中的代码:
respond_to do |format|
format.html # show.html.erb
format.js
end
View 中的代码、链接和 JavaScript:
<%= link_to "Show analysis", company_comparison_path(3), :remote => true , :id => "thelink" %>
<div id="replaced"> will be replaced </div>
<script>
$('#thelink').bind('ajax:complete', function() {
$('#replaced').html(data)
});
</script>
我想我还是不明白如何将 Controller 中的 HTML 或 JavaScript 正确地返回到 JavaScript 中。如果我用括号中的一些文本替换 JavaScript 中的“数据”一词,我会得到正确的输出。但是如何从 Controller 操作中获取结果呢?
最佳答案
您快完成了,但是您需要告诉绑定(bind)函数您想插入到#results div 中的实际 html 内容是什么。当您在 $('#replaced')
上调用 .html()
时,您使用的变量 (data
) 仍未定义。
尝试以下操作:
$('#thelink').bind('ajax:complete', function(event, data) {
$('#replaced').html(data.responseText);
});
编辑:哦,要记住的一点是,这可能会呈现您的 View ,包括可能不是您想要的布局。您可以向 Controller 添加类似 render layout: false if request.xhr?
的内容,以防止布局显示在 ajax 请求中。
关于html - AJAX 调用后显示数据,如何在 Controller 中呈现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12449300/