我正在使用rails 3.1,我正在使用ajax创建一个搜索表单,我已经使用post方法处理表单了,我在这里遗漏了一些东西...... 所以在我看来我有
<%= 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
然后在同一视图中返回db中找到的参数
<%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>
我想要实现的是同样的创建查询到数据库,但使用ajax,因此不需要在页面中重新加载。 第一个问题,我必须从javascript中的某个地方处理数据,在哪里? 第二个问题,我如何在返回时处理数据
我完全迷失在使用Rails的Ajax中,所以任何帮助/提示都会非常感激。 提前致谢。 抱歉我的英语很糟糕。
答案 0 :(得分:2)
您的submitWithAjax函数正在调用serialize(),它为您准备表单数据。
表单操作的控制器需要响应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
答案 1 :(得分:0)
使用Rails本机ajax实用程序处理此问题最容易。换句话说,您的表单标记应如下所示(请注意remote
参数):
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
}
请参阅Rails 3.1文档,了解其他ajax回调,例如ajax:complete
和ajax:error
等。