In a Rails app, how can I make a link load in a div as opposed to refreshing the whole page?
I'm still a beginner at web development. It's not my profession. So go easy.
I started building a rails app today, and realized it would make my application so much better if I could get certain links to display in a separate div instead of a new page, or refreshing the entire page. I'm not quite sure how to search for this, and I keep chasing red herrings with google.
Basically, I have a list in a div on the left side of the page, and when one item from that list is clicked, it should appear in the right div. (N开发者_JS百科othing else on the page need be changed)
That's really as simple as it is. Do I need to use Javascript for this? Can I get away with the rails js defaults, or should I be using JQuery?
Is there a way to do this without javascript? I really just need a push in the right direction here, I'm tired of not even knowing how to search for this, or what documentation I should be reading.
Like I said, go easy, and you should just go ahead and err to the side of caution, and assume I know nothing. Seriously. :)
Thanks in advance,
-Kevin
(By the way, I'm developing with Rails 3)
Create your views (along with controllers) to be shown inside the div for each item on the left menu. Lets say we have the following structure now:
- Item1 (Clicking on it will fetch: http://myapp.com/item1)
- Item2 (Clicking on it will fetch: http://myapp.com/item2)
and so on...
make sure you only render the html to be put inside your content div. Should not include <head> <body> etc.
tags
In your main page you may have your markup like this >
<div id="leftMenu">
<a href="http://myapp.com/item1">Item 1</a>
<a href="http://myapp.com/item2">Item 2</a>
</div>
<div id="content">
Please click on an item on the left menu to load content here
</div>
Finally, add the following Javascript (you'll need jQuery; trust me it's a good decision).
$("#leftMenu a").click(function () {
$("#content").load($(this).attr("href")); //load html from the url and put it in the #content element
return false; //prevent the default href action
});
You will need JavaScript if you want to avoid reloading the page. You can use link_to
for links in your lists, and you'll need to use :remote => true
to make it send AJAX requests to the server. The server will need to respond appropriately and supply HTML for your div.
link_to
documentation is here: http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to (and admittedly it isn't very useful for AJAX functionality).
The last post in this thread shows one possible solution you could use.
精彩评论