Javascript Rails 3.2使用Ajax更新操作。

Javascript Rails 3.2使用Ajax更新操作。,javascript,ruby-on-rails,ajax,ruby-on-rails-3,Javascript,Ruby On Rails,Ajax,Ruby On Rails 3,我正在尝试使用Ajax为Rails 3.2应用程序创建一个更新表单。我是Ajax初学者,所以我需要一些指导。我想要实现的是: 1. The user presses a button and a form slides down from the top in a div. 2. The user updates the form and presses "update". 3. The parameters from the updated form is sent and saved to

我正在尝试使用Ajax为Rails 3.2应用程序创建一个更新表单。我是Ajax初学者,所以我需要一些指导。我想要实现的是:

1. The user presses a button and a form slides down from the top in a div. 
2. The user updates the form and presses "update".
3. The parameters from the updated form is sent and saved to the database, and 
4. the form slides up again without making the user leave the page.
该表单当前如下所示:

<%= form_for(@user, :remote => true) do |f| %>
  <%= render 'shared/error_messages' %>
  <%= f.fields_for :oak do |oak| %>
    <%= oak.text_field :name, :placeholder => "Name" %>
  <% end %>
  <%= f.fields_for :energy_meter do |energy_meter| %>
    <%= energy_meter.text_field :energy_meter_id, :placeholder => "Id" %>
  <% end %>
  <%= f.submit "Update!", "data-role" => "button", "data-theme" => "b", "return" => "false" %>
<% end %>  
def update
  @user = current_user
  @user.update_attributes(params[:user])
end 
它位于我的UsersController中

我还有一个update.js.erb文件,当前看起来像这样:

$(window.location.replace("/"))
我不知道应该用update.js.erb做什么,也不知道如何发送参数,它目前只重定向到
/
。我还想知道在我的更新操作中应该放在哪里以及放什么,它当前位于UsersController中,但它应该位于我的表单所在的PagesController中吗

任何提示或指导都会很好


谢谢

将以下代码添加到
aaapplication.js

$("#BUTTON_ELEMENT").live("click", function() {
    $("#FORM_ELEMENT").slideDown();
});

$("#FORM_ELEMENT").live("submit", function() {
    var _form = $(this);
    $.post(_form.attr("action"), _form.serialize(), function() { _form.slideUp(); }, "script");
    return false;
});

出于测试目的,向
update.js.erb

添加一些警报。您应该向控制器添加
respond\u to
块,并添加
format.js
,以便控制器随后呈现
update.js.erb
文件

您不需要这一行:

$(window.location.replace("/"))

默认情况下,
AJAX
调用时,URL不会更改。

我不确定这是否适用于这种情况,但如果这类似于使用jquery创建搜索字段。。。我想你应该把这段代码放在update.js.erb中

$('#DIV_ID').html('<%= escape_javascript(render("update")) %>');
$('#DIV_ID').html('';
其中“update”是包含表单的_update.html.erb文件,“#DIV_ID”是要呈现表单的DIV

也许这位铁路司机能比我解释得更好,希望能有帮助。

嗨,我有警报要显示。但它会重定向到/users/1。我的更新操作当前看起来如下:
def update@user=current\u user respond\u to do | format |@user.update_attributes(params[:user])format.js{render:layout=>false}end
。并显示未定义的文本。确保您在
应用程序中提供了正确的
表单id
。js
还可以在控制台上检查提交表单时发送的请求(即js或HTML)。由于某些原因,is会重定向到/users/1。这就是为什么我加了上面这一行。我不知道如何使其不重定向到该url,它似乎呈现了我的update.js.erb文件。我认为在按钮/链接上添加
event.preventDefault()
可能会阻止它重定向到
/users/1
。见: