如何检查用户电子邮件的唯一性并将结果传递给jQuery?

我有这个问题:我正在检查控制器中的用户电子邮件并发送json成功响应,如果已经采取并添加输入的CSS样式,我也需要阻止提交并添加一些消息。

这是我的checkemail行动(使用这篇文章 – http://paydrotalks.com/posts/45-standard-json-response-for-rails-and-jquery ):

def checkemail if !User.where('email = ?', params[:email]).empty? format.jsonr do render :json => { :status => :ok, :message => "Success!", }.to_json end end end 

在我的路线:

  checkemail GET /checkemail(.:format) match "/checkemail", to: 'edit_user#checkemail' 

和我的jQuery:

  $('#user_email').focusout(function() { $.getJSON('/checkemail', { email: $('#user_email').val() }, function(data) { $('#user_email').addClass("error"); }); }); 

我的HTML输入代码:

   

来自mime_type初始化文件:

  Mime::Type.register_alias "application/json", :jsonr, %w( text/x-json ) 

来自Fiddler:

  Request : GET /checkemail?user@mail.com HTTP/2.0 Response(RAW tab) : Missing template edit_user/checkemail JSON tab is empty 

问题:如何检查是否发送了json请求? 如何阻止提交表单并添加一些消息?

我会这样做:

 $('#element').focusout(function() { $.getJSON('PATH_TO_EMAIL_CHECK_ACTION', { email: $('#element').val() }, function(data) { // The data should tell you if its unique or not, you do something // here depending on response }); }); 

在控制器中,检查是否已收到电子邮件。 如果不是,则发送回状态为OK并且消息成功的渲染json。 您可以检查评论中的状态是否成功。

jquery focusout – http://api.jquery.com/focusout/

jquery getJSON – http://api.jquery.com/jQuery.getJSON/

关于控制器中的json响应 – http://paydrotalks.com/posts/45-standard-json-response-for-rails-and-jquery