2012-01-08 50 views
1

林轨3.1,我创建使用Ajax搜索表单,我已经用POST方法的工作形式,我缺少的东西在这里... 所以,在我看来,我有的Ajax查询和Ruby on Rails

<%= 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 %> 

好吧,我在application.js中写了一些东西来处理提交事件。

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(); 
}) 

控制器会重新设置表单中的参数,并像这样创建对数据库的查询。

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

,然后返回在数据库中找到同一视图

<%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> 

的参数我想实现的是相同的页面创建一个查询到数据库,但与阿贾克斯所以没有重装是必要的。 第一个问题,我必须从JavaScript中的某处处理表单中的数据,在哪里? 第二个问题,就是当回

我完全在Ajax和Rails的丢失,所以任何帮助/提示将非常赞赏我怎么处理数据。 在此先感谢。 对不起,我的英文很糟糕。

回答

2

您对submitWithAjax功能调用序列化()的准备表单数据为您服务。

您的表单操作控制器需要响应format.js ABOVE format.html,并且您需要一个与“.js.erb”扩展名相应的视图文件夹中的操作名称匹配的文件。

在这一“.js.erb”文件,你可以调用任意jQuery来代替内容,改变页面的元素,或触发动作。其他

$('#lightBoxClose').trigger('click'); 
$('#flashContentContainer').html('<%= escape_javascript(render :partial => "shared/flash_bar") %></div>'); 

的一件事是,以确保您的应用程序与format.js行动响应你可以改变你submitWithAjax功能,像这样:

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

注意”的.js'。

如果你还没有看到它退房this railscast

0

这是最简单的使用Rails本地AJAX工具来处理这个问题。换句话说,你的表单标签应该是这样的(注意remote PARAM):

form_tag(root_path, :method => "post",:id =>"formid", :remote => true) 

这是所有你需要通过AJAX发布。但是,你需要处理这个回应。在JavaScript文件中,这样做:

$('#formid') 
    .bind('ajax:success', function(response) { 
     // response is what gets sent from the controller 
     // so send only the dynamic data and insert it into the DOM 
    } 

看到其他AJAX回调像ajax:completeajax:error等了Rails 3.1的文档。