【问题标题】:Rails 3 - Bind Pre-AJAX RequestRails 3 - 绑定 Pre-AJAX 请求
【发布时间】:2011-01-12 03:19:30
【问题描述】:

我目前正在尝试使用 button_to 来触发对记录的更新。由于 AJAX 请求需要一些时间,我将通过在发送请求之前更新 UI 来模拟请求的 UI 效果。跟随this post 对link_to 执行类似的操作。

在我看来,我有:

button_to "Submit", my_class_path, :remote => true, :class => "my_class", :method => :get

在 application.js 我有以下内容:

jQuery(function($) { 
  $("input.my_class").bind("ajax:loading",  function(){
    alert("Hello World!");
  });
});

事件要么没有被触发,要么我没有正确绑定到它。如何处理来自 button_to 的 pre-AJAX 请求?

顺便说一句,有没有一种很好的方法可以在 javascript 事件被触发时查看它们?

【问题讨论】:

    标签: ruby-on-rails ajax event-handling ruby-on-rails-3


    【解决方案1】:

    问题可能是button_to 创建了这样的东西:

    <form method="post" action="/some_action" data-remote="true" class="button_to">
    <div>
        <input name="_method" type="hidden" value="delete">
        <input class="my_class" type="submit" value="Submit">
        <input name="authenticity_token" type="hidden" value="asdfasdfasdfsafasdfasdfas=">
    </div>
    </form>
    

    但是根据rails.js,看起来ajax请求被绑定到包含表单:

    $('form[data-remote]').live('submit', function (e) {
        $(this).callRemote();
        e.preventDefault();
    });
    

    所以本质上,输入按钮只是提交表单,rails.js 代码捕获并用于执行 ajax 调用。这可能意味着您必须直接绑定到按钮的表单。像这样的:

    $("input.my_class").parents('form[data-remote]').bind("ajax:loading",  function(){
        alert("Hello World!");
    });
    

    【讨论】:

    • 工作就像一个魅力!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2012-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-02
    • 1970-01-01
    • 2011-04-30
    • 1970-01-01
    相关资源
    最近更新 更多