I want to render html partial with js respond_to
Here is my controller:
class SearchesController < ApplicationController def index @users = User.ransack(first_name_or_last_name_cont: params[:query]).result(distinct: true) @teams = Team.ransack(name_cont: params[:query]).result(distinct: true) respond_to do |format| format.js {} format.json {} @users = @users.limit(5) @teams = @teams.limit(5) end end end
Here is my index.js.erb:
$('<%= j render :partial => 'result_list' %>')
It works but it don't display html correctly in my search dropdown
I have something like this:
$(' \\n\\nUsers\\n<\\/span>\\n\\n\\n<\\/i>\\n<\\/span>\\nCharlotte Marie<\\/span>\\n<\\/a>\\n\\n\\n<\\/i>\\n<\\/span>\\nMatrice .io<\\/span>\\n<\\/a>\\n\\n\\n\\"Maboukra\\"\\n<\\/span>\\nMichael Aboukrat<\\/span>\\n<\\/a>\\n\\n\\n<\\/i>\\n<\\/span>\\nConstance Albanel<\\/span>\\n<\\/a>\\n\\n\\n\\"Malberte\\"\\n<\\/span>\\nMatthieu
Please let me know the right js code
You're rendering the whole HTML partial directly into the $() tag, which is not correct. Keep in mind that what Rails does is to load the Javascript inside the js.erb
file.
Instead, you should load it into another HTML element, something like:
<span id="container"></span>
and then, make the HTML inside it to be the partial you want to render, so in the index.js.erb
you should write:
$('#container').html("<%= j render partial: 'result_list' %>");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.