如何检查用户电子邮件的唯一性并将结果传递给jQuery? [英] How to check user email uniqueness and pass result to jQuery?

查看:93
本文介绍了如何检查用户电子邮件的唯一性并将结果传递给jQuery?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个问题:我正在检查控制器中的用户电子邮件,并发送json成功响应(如果已被接受),并添加输入的CSS样式,我还需要防止提交和添加一些消息.

I have this problem : I'm checking user email in controller and sending json successfull response if it is already taken and add css styling of input, also I need to prevent submit and add some message.

这是我的checkemail操作(用于本文- http://paydrotalks.com/posts/45-standard-json-response-for-rails-and-jquery ):

Here is my checkemail action ( used this article - 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输入代码:

my HTML input code:

     <input id="user_email" name="user[email]" size="30" type="email" value="">

来自mime_type初始化程序文件:

from mime_type initializers file:

    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且消息成功的render json.您可以在上面注释上方的回调中检查状态是否成功.

And in the controller, check if the email is taken. If its not, send back render json with status OK and message success. You can check if the status is success in your callback where the comment is above.

jquery焦点输出- http://api.jquery.com/focusout/

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

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

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

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

About json responses in controller - http://paydrotalks.com/posts/45-standard-json-response-for-rails-and-jquery

这篇关于如何检查用户电子邮件的唯一性并将结果传递给jQuery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆