我正在尝试使用 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”表单?