使用Prototype在Rails 3中实现Ajax回调,而非jQuery

3

我正在将一个应用从Rails 2升级到3,并重新设计所有远程功能以使用Unobtrusive Javascript。 我遇到困难的地方是处理UJS中的ajax回调。

我找到了很多资源,展示了如何使用jQuery实现这些回调,但对于prototype而言并不多。也许你可以帮我解决这个问题。

在Rails 2中,我有这样的代码:

<% remote_form_for @foo, {:loading => "loading_function()", :complete => "complete_function()" } do |f| %>
 ...
<% end %>

在Rails 3中,我有以下代码:
<%= form_for @foo, :remote => true do |f| %>
 ....
<% end %>

据我目前了解的情况(可能有误),我需要将旧的loading/complete函数附加到表单上,以便它们可以被Rails.js中的handleRemote函数触发。只是我不确定该如何操作。

再次说明,我正在使用Prototype框架。因此,特定于该框架的答案将不胜感激。

4个回答

5
答案如下:
<%= form_for @foo, :remote => true do |f| %>
 ...
<% end %>
...
<script type='text/javascript'>
  $('edit_foo').observe('ajax:before', loading_function());
  $('edit_foo').observe('ajax:complete complete_function());
</script>

0
尝试使用链接。是的,它是JQuery,但JQuery和Prototype在如何协同工作方面没有区别。这里有一个代码片段,在索引页面直接添加新任务 - 它使用Prototype:
views/tasks/_newform.html.erb:
<%= form_for(@task, :remote => true) do |f| %>
  <div>
    <%= f.label 'Add a new task: ' %>
    <%= f.text_field :name %>
  </div>
  <div>
    <%= f.submit %>
  </div>
<% end %>

views/tasks/index.html.erb:
<div id='newform'>
  <%= render :partial => "newform", :locals => { :@task => Task.new } %>
</div>

views/tasks/create.js.rjs:
page.insert_html :after, 'tablehead', :partial => @task
page.replace_html 'newform',:partial => "newform", :locals => { :@task => Task.new }

编辑:您需要将“format.js”添加到任务控制器的创建方法中


0

对于遇到类似问题的人,查看Rails 2.3.x源代码中远程助手的源代码可能会有所帮助。

在我的情况下,我想知道该怎么处理':update'参数,例如:

remote_form_for(@obj, :update => "new_obj", :before => "some js code") do |f|

我必须在remote_function code中找到更新功能。


针对我的具体问题,看起来用 Rails 3 UJS 助手无法获取与 :update 等效的内容。Rails 3 中的 rails.js 会利用 Ajax.Request(...) 包装 :remote => true 请求,而 Rails 2 中的 :update 函数将 Ajax 请求包装在 Ajax.Updater(...) 中。对于想要替换 Rails 2 中的 :update 功能的人,我看到有两个选择:

  • 转换到 jquery-rails,这样您可以通过以下代码访问 Ajax 请求的响应:

    $("#elem").bind("ajax:complete", function(et, e){
      $("#results").html(e.responseText);
    });
    
  • 编写自己的基于 Prototype 的代码来获取表单并通过 ajax 提交它,使用 Ajax.Updater(...) 而不是 Ajax.Request。不要使用:remote => true,因为这将尝试使用 Ajax.Request

顺便提一下:我尝试使用ajax:complete事件中提供的回调对象进行操作。

$('new_obj').observe('ajax:complete', function(request){
  console.info(request);
});

request 对象似乎没有包含响应的任何信息。虽然它非常庞大,但我可能是错的。希望这能帮助其他尝试从 Rails 2 升级到 3 的人。


0

如果您正在使用带有:update选项的remote_form_for,那么有一种方法可以从Ajax.Request调用中获取响应。因此,您可能不需要将其更改为使用Ajax.Updater作为解决方法。基本上,您可以使用response.memo.responseText,例如,在您的示例中,它可能是这样的:

$('new_obj').observe('ajax:complete', function(response){
  console.info(response.memo.responseText);
  // Probably you would use it like this:
  $('new_obj').update(response.memo.responseText);
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接