Ajax查询和Ruby on Rails

Im using rails 3.1, and I am creating a search form with ajax, I have already the form working with a post method, I am missing something here... So in my view I have

<%= form_tag(root_path, :method => "post",:id =>"formid") do %>
  <%= label_tag(:number1, "El que quiero") %>
  <%= text_field_tag :quiero, nil, :class => 'drug_autocomplete' %>
  <%= hidden_field_tag :number1 %>

  <%= label_tag(:number1, "El modelo que tengo") %>
  <%= text_field_tag :tengo, nil, :class => 'drug_autocomplete' %>
  <%= hidden_field_tag :number2 %>

  <%= label_tag(:size1, "Talla de el que tengo") %>
  <%= text_field_tag :size1%>

  <%= submit_tag("Do it!") %>

<% end %>

Ok and I wrote in the application.js something to handle the submit event.

jQuery.ajaxSetup({ 
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
})

jQuery.fn.submitWithAjax = function() {
  this.submit(function() {
    $.post(this.action, $(this).serialize(), null, "script");
    return false;
  })
  return this;
};

$(document).ready(function() {
  $("#form_id").submitWithAjax();
})

The controller recibes the parameters in the form, and create a query to the database like this.

@itemsok = Contribution.where("first_item_id = ?",item1.id).where("second_item_id = ?",item2.id).where("second_item_grade = ?",size1

And then returns the parameters found in the db in the same view

<%if not @itemsok.nil? 
  @itemsok.each do |searches|
%>
<table>
<tr>
  <td style="width:100px;"><%= searches.first_item.description %>  </td>
  <td style="width:150px; font-size:30px;"><%= searches.first_item_grade %>  </td>


  <td style="width:150px;"><%= searches.second_item.description %> </td>
  <td style="width:150px; font-size:30px;"><%= searches.second_item_grade %>  </td>
  <td style="width:150px; font-size:18px;"><a href="<%= contribution_path(searches.id) %>">Show</a>  </td>


</tr>
</table>

What I want to achieve is the same creating a query to the database but with ajax so no reload in the page is needed. First question, I have to handle the data from the form somewhere in the javascript, where? Second question, how do I handle the data when is back

I am totally lost in Ajax with Rails, so any help/hint would be very appreciated. Thanks in advance. Sorry for my terrible english.

查看全部
weixin_33739523
weixin_33739523
2012/01/08 18:40
  • ruby-on-rails
  • ajax
  • jquery
  • ruby
  • 点赞
  • 收藏
  • 回答
    私信

2个回复