【问题标题】:jquery-ujs ajax events are not handledjquery-ujs ajax 事件未处理
【发布时间】:2011-02-09 20:43:19
【问题描述】:

我正在尝试使用 rails 3 实现 ajaxy 注册。我正在使用 jquery-ujs 和远程表单。我使用$.get 请求访问注册表单,它显示正确。此注册表单是远程的:

form_for @user, :remote => true, :html => {"data-type" => "html"} do |f|

在我的 application.js 中,如果获取表单的 ajax 请求成功,我正在尝试从不显眼的 javascript 绑定 ajax 事件处理程序:

var load_remote_form = function(evt) {
    var href = $(this).attr('href'); 
    // load form template
    $.get(href, {}, function(data) {
        $('body').append(data);

        $('form[data-remote]').bind("ajax:beforeSend", function(e) {
            console.log("Caught beforeSend!");
        });
    });
    evt.preventDefault();
};

$(document).ready(function() {
    $('a#signup').click(load_remote_form);   
});

Chrome 的开发工具显示事件“ajax:beforeSend”已绑定,但从未处理(当我发送表单时,javascript 控制台中没有任何内容,尽管在 rails 日志中我看到请求已正确处理并且响应是发送)。我可以将其他事件绑定到同一个选择器 (form[data-remote]),例如 click,并且它们被正确处理。

通过.live 绑定的Ajax 事件也不会被处理。但是,如果表单作为布局的一部分呈现(即它位于像 http://localhost:3000/signup/ 这样的独立页面上),则正确处理绑定的“ajax:beforeSend”。

我的控制器(只是为了一个案例,它可能写得不好,但我很确定它可以工作):

class UsersController < ApplicationController

  layout :layout_for_type

  def new
    @user = User.new
  end

  def create
    @user = User.new(params[:user])
    if @user.save
      session[:user_id] = @user.id
      flash[:notice] = "You have successfully registered."
      redirect_to root_url
    else
      if request.xhr?
        render :action => 'new', :status => :unprocessable_entry, :layout => false
      else
        render :action => 'new'
      end
    end
  end

  def layout_for_type
   request.xhr? ? nil : "application"
  end

end

我做错了什么?是否有更好的方法来实现这种“双 ajaxed”表单?

【问题讨论】:

    标签: ruby-on-rails-3 jquery ujs


    【解决方案1】:

    我傻了。我完全忽略了另一个潜在的问题来源。我有

    javascript_include_tag :all
    

    在我的应用程序布局中,这导致在我的页面中包含 both jquery.jsjquery.min.js。事实证明,这是导致这种奇怪行为的原因。删除jquery.min.js 就成功了。希望有一天对某人有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多