[英]Rails: loading partial with jQuery
I wanna show the search results dynamically by requesting the action which returns a javascript, which loads the partial. 我想通过请求返回javascript的动作来动态显示搜索结果,该动作加载部分。 I have done some reading and escape_javascript seems like a right way to do it. 我做了一些阅读和escape_javascript似乎是一个正确的方法来做到这一点。 But nothing shows up and I get 500 internal server error. 但没有任何显示,我得到500内部服务器错误。
Here is some code 这是一些代码
in controller: 在控制器中:
def search
@user = User.find_by email: params[:email]
respond_to do |format|
if @user && @user.user_type_type == "Employee"
format.js
else
format.js {render "failed_search"}
end
end
end
view with the search form: 查看搜索表单:
<div id="search-employee">
<%= form_tag({controller: "employees", action: "search"}, method: :get, remote: true) do %>
<%= label_tag 'email', "Search for:" %>
<%= text_field_tag 'email'%>
<%= submit_tag("Search") %>
<% end %>
<div id="search-result" class="row">
</div>
</div>
js returned by the action (works when I put plain text to html instead of escaping js) 动作返回的js(当我将纯文本放到html而不是转义js时工作)
$('#search-result').html("<%= escape_javascript(render :partial => 'employees/search_result') %>");
I would show you the partial, but it does not get rendered even when I put plain text there, so it is not that. 我会告诉你部分,但即使我把纯文本放在那里也不会被渲染,所以不是那样。
Here is the output from the console, indeed it looks informative, I must have missed it. 这是控制台的输出,确实它看起来很丰富,我一定错过了它。
Completed 500 Internal Server Error in 10ms (ActiveRecord: 0.2ms)
ActionView::Template::Error (Missing partial employees/_search_result.html.erb with {:locale=>[:en], :formats=>[:js, :html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}. Searched in:
* "/home/johnny/Desktop/ror/pub_crawler/pub_crawler_1.2/app/views"
* "/home/johnny/.rvm/gems/ruby-2.2.1@rails4.2/gems/devise-3.5.6/app/views"
):
1: //does not work
2: $('#search-result').html("<%= escape_javascript(render :partial => 'employees/search_result.html.erb') %>");
3:
4: $('#search-result').html('<div class="col-3-md"><%= @user.user_type.name %></div> <div class="col-3-md"><%= @user.user_type.surname %></div> <div class="col-3-md"></div>');
app/views/employees/search.js.erb:2:in `_app_views_employees_search_js_erb__3438283462284537863_70351967525560'
app/controllers/employees_controller.rb:12:in `search'
EDIT: ok, I'm a moron, It was a typo in file name... 编辑:好的,我是个白痴,这是文件名中的拼写错误...
Could you post the output from your rails console and the search_result partial? 你可以发布rails控制台和search_result部分的输出吗? I suspect that Rails either can't find your partial file, or the partial is trying to use a variable that is undefined. 我怀疑Rails要么找不到你的部分文件,要么部分试图使用未定义的变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.