I am trying to get the idea of AJAX rendering a template into the index page. Can anyone help me understand how Rails render "next.js.erb" rather than looking for "next.html.erb"?
routes.rb
get 'index' => 'products#index'
get 'next' => 'products#next'
index.html.erb
<%= @products.first.price %>
<%= link_to "Next", action:"next", remote: true %>
<div class="box"></div>
next.js.erb
(".box").html(<%= j render("nextitem") %>
_nextitem.html.erb
<%= @products.second.price %>
In products_controller.rb:
def index
@products = Product.all
end
def next
@products = Product.all
respond_to do |format|
format.html { redirect_to root_path }
format.js
end
end
I'd start off by adding a resources route to your routes.rb
page instead of specifying every unique route:
resources :products, only: [:index] do
member do
post 'next'
end
end
Then your index.html.erb
page's link can look like:
<%= link_to "Next", next_product_path(@product), remote: true %>
Your products_controller.rb
needs to specify a specific @product
in the def next
method, which you can pull from your @products
collection (you can find the last product you displayed and retrieve the next one, or however you wish to do it).
next.js.erb
can then do this (which renders the _next_item.html.erb
partial, passing the @product
instance variable defined in the controller as a local variable named product
):
$(".box").html("<%= j render 'nextitem', product: @product %>");
And lastly in _nextitem.html.erb
you can simply format the product
local variable however you want it in the html before it's rendered and replaces what you currently have on your page, ie:
<div><%= product.price %></div>
Please let me know if you have any questions or if anything wasn't quite clear enough!
-Dave
将next.js.erb更改为:
$(".box").html("<%=j render 'nextitem ' %>")
If you simply request the page at /next
, it will look for an html.erb
template. To render a js
template, you need to append .js
at the end of request like localhost:3000/next.js
. And the same is true for JSON response. For a JSON response, you need to append .json
at the end of the URL.
Or if you are using jQuery to fetch the response from the server, you need to pass dataType: script
to render JS format instead of HTML format.
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.