假设我有一个名为“search”的应用程序方法,我希望它能够响应AJAX请求。在我的JS视图中(app/views/application/search.js.erb),我想要呈现HTML视图:
$("#content").html( escape_javascript( render( :action => 'search', :format => 'html' ) ) );
$("#title").html( "Title" );
我知道我可以将内容移到一个partial中,并在HTML和JS视图中呈现它,但问题是我有许多不同的操作需要以这种方式响应,我不想创建一堆只呈现partial的1行视图文件。
有没有办法显式地呈现具有特定格式的操作并抓取content_for的不同部分?因此,对于上面的示例,我可以使用content_for:title设置#title为返回的HTML或类似的内容。
escape_javascript(render: action_name, format => 'html')
来类似地渲染HTML。 - mswieboda$('#content').html(escape_javascript('<%= render action: 'search', format: 'html' %>'));
http://api.rubyonrails.org/classes/ActionView/Helpers/JavaScriptHelper.html#method-i-escape_javascript - ChuckJHardy:formats => ['html']
而不是:format => 'html'
。请参见此处:https://dev59.com/b3RC5IYBdhLWcg3wUfN2。这个问题应该在较新版本的Rails中得到解决,请参见此处:https://github.com/rails/rails/issues/4841。 - Samuel