问题
I am using ruby on rails and I would like to render a partial on click (using jquery) an example of this being:
$('#submit').on('click', function(){
$('#lol').append("<%= escape_javascript(render :partial => 'myPartial' ) %>");
}
I basically want to submit a form then show the results (render partial) after in a read only format without the page refreshing. Problem is I can't use render in the asset pipeline. How do I include my JavaScript file from the view folder or what would be a good solution for this issue?
回答1:
Looking at your code
$('#submit').on('click', function(){
$('#lol').append("<%= escape_javascript(render :partial => 'myPartial' ) %>");
}
I think you are confusing between ajax and normal jquery. If you don't need to perform anything else then you should use normal jquery to show and hide your content. For that you need to put this code in your app/assets/javascript/application.js or make a new file then require it inside application.js like
//= require file_name
Inside your view you can hide the parent element of your content by giving it a style like this:
#your_content_container{
display: none;
}
Then place your jquery code in your_file.js
$(document).on("click","#submit",function(){
$("##your_content_container").show();
})
If it's a form as your question says then you need to to perform some logic in your controller too so you should use Ajax
Since it's a form so you need to use remote: true option in your form something like:
<%= form_for(@user, remote: true) do |f| %>
// your fields
<% end %>
and then inside your controller you can have
def your_method
#do your logic here
respond_to do |format|
format.js{}
end
end
This will allow rails to look for a file named your_method.js.erb in your views where you can call your jquery and render your partial. In your_method.js.erb
$('#lol').append("<%=j render :partial => 'myPartial' %>");
For details refer to Working with Javascript in Rails
来源:https://stackoverflow.com/questions/24613684/how-to-use-js-file-within-view-folder