Rails: Using JQuery to display results of a form submit button calling another page?
I've got my first Rails application working! I have a text-field for a user to enter a sentence, and then from that sentence, I use:
form_tag(another_page, :method => "get")
to send the text-field value into another page, which calls a class I made and plays around with the sentence structure.
Now, I want to take it one step further! I want to be able to use JQuery (maybe the .load command?) to display the results on the same page, without having to load a completely separate page. (I'm going to eventual开发者_运维百科ly make it so each new sentence is pushed down one (using .prepend) and the newer sentence appear at the top.)
My two questions are: Is this an acceptable way of doing it (using JQuery to load the contents of another page)? And, most importantly, how do I modify my code to do this?
I'm familiar with some JQuery, but I don't know how to, for example, change the form submission in Rails to not load a new page (and instead get that new page in a JQuery.load call).
Thanks, Derek.
Derek, welcome to Rails!
First of all, yes using jQuery is a great idea.
There are a few ways to do it. You can write straight jQuery and in an external javascript file call (or something like this):
$('#form_id').submit(function(e) {
e.preventDefault();
$.ajax({
dataType: 'json',
url: $this.attr('action'),
type: $this.attr('method').toUpperCase(),
data: $this.serialize(),
success: function(data) { /* Do Stuff */ }
})
});
Or rails has some helpers that do some of this for you so that all you have to do is say form_tag(another_page, :method => "get", :remote => true)
. For this you do need to include the rails.js
file on your page as well (here's a good article on it : http://www.alfajango.com/blog/rails-3-remote-links-and-forms/)
Does that help?
精彩评论