Rails 3.1远程按钮不引人注目的Javascript事件未被捕获(JQuery)

Jam*_*ath 2 jquery unobtrusive-javascript ruby-on-rails-3 ruby-on-rails-3.1

我想开始使用Ajax事件ajax:success,ajax:failure,ajax:complete和ajax:beforeSend,建议用于以下帖子中的不显眼的Javascript:

但由于某种原因,它不适合我.我错过了一些东西(小东西),因为我无法让事件触发我的Javascript.我希望有人能在我的代码中发现"明显的"错误/遗漏.

关于我的环境的一些细节:

  • Rails 3.1
  • jQuery(jquery-rails gem)
  • 用于服务器端js处理的therubyracer(不是说它对我的例子来说很重要)

为了尝试找出我所缺少的东西,我创建了一个简单的测试应用程序,它只有一个远程按钮.单击按钮时,我想要触发警报框.这个应用程序的代码可以在github上看到:

http://github.com/jpmcgrath/rbtest

我已将应用程序部署到heroku:

http://rbtest.heroku.com/projects/

如果你查看应用程序,你可以单击按钮,按钮成功创建一个新项目(看它手动刷新),但ajax:成功事件似乎不会发生?

代码的内容如下:

在projects_controller.rb中

def remote_test
  @project = Project.new(:name => "remote test")

  respond_to do |format|
    if @project.save
      puts "project saved!\n\n\n"
      format.html { redirect_to @project, notice: 'Project was successfully created.' }
      format.json { render json: @project, status: :created, location: @project }
    else
      format.html { render action: "new" }
      format.json { render json: @project.errors, status: :unprocessable_entity }
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

在application.js中

jQuery(document).ready(function() {

  jQuery(".remote_button").click(function() {
    alert('Handler for .click() called.');
  })
  .bind("ajax:complete", function() {
    alert('complete!');
  })
  .bind("ajax:beforeSend", function () {
    alert('loading!');
  })
  .bind("ajax:error", function (xhr, status, error) {
    alert('failure!');
  })
  .bind('ajax:success', function(event, data, status, xhr) {
    alert('success!');
  });
});
Run Code Online (Sandbox Code Playgroud)

在视图projects/index.html.erb中

<%= button_to "remote test", remote_test_path, :remote => true, :class => 'remote_button'  %>
Run Code Online (Sandbox Code Playgroud)

如果有人能够指出我缺少的东西(我怀疑它与响应类型有关),我将不胜感激.

Clu*_*ter 9

您的事件处理程序未触发的原因是您的选择器位于错误的元素上.button_to创建一个带有单个输入标记的表单,它是具有您选择的类的输入标记,但是在表单上触发了ajax事件,而不是输入标记.

试试这个

jQuery(document).ready(function() {

  jQuery(".remote_button").click(function() {
    alert('Handler for .click() called.');
  });

  jQuery("form.button_to").bind("ajax:complete", function() {
    alert('complete!');
  })
  .bind("ajax:beforeSend", function () {
    alert('loading!');
  })
  .bind("ajax:error", function (xhr, status, error) {
    alert('failure!');
  })
  .bind('ajax:success', function(event, data, status, xhr) {
    alert('success!');
  });
});
Run Code Online (Sandbox Code Playgroud)

我在我的firebug控制台中做了相同的操作,当回调在表单上时,它触发了ajax:success处理程序.

要更改表单上的类,请使用:form_class选项将其从button_to更改为其他内容

<%= button_to "remote test", remote_test_path, :remote => true, :class => 'remote_button', :form_class => 'remote_button_form' %>
Run Code Online (Sandbox Code Playgroud)

然后使用添加你的ajax回调

jQuery(".remote_button_form").bind ...
Run Code Online (Sandbox Code Playgroud)

http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-button_to