检查用户名可用性

dem*_*mas 6 ajax ruby-on-rails

我有一个用户登录表单:

<%= form_tag(@action, :method => "post", :name => 'signup' ,:onSubmit => 'return validate();') do %>    
  <%= label_tag(:user, "Username:") %>
  <%= text_field_tag(:user) %>
Run Code Online (Sandbox Code Playgroud)

我想在以后检查数据库中是否有用户名:user-field lost focus.我可以使用javascript在表单上覆盖此事件,但我无法从javascipt代码发送Ruby-AJAX请求.

有没有办法检查用户名而不在表单上添加其他控件(按钮,链接)?

Via*_*kov 35

您可以使用一些JavaScript(这是用jQuery编写的)用于AJAX cheking:

$(function() {
    $('[data-validate]').blur(function() {
        $this = $(this);
        $.get($this.data('validate'), {
            user: $this.val()
        }).success(function() {
            $this.removeClass('field_with_errors');
        }).error(function() {
            $this.addClass('field_with_errors');
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

此JavaScript将查找具有属性的任何字段data-validate.然后它确定onBlur事件处理程序(焦点在JavaScript世界中丢失).在模糊处理程序中,将AJAX请求发送到data-validate属性中指定的URL,并user使用输入值传递参数.

接下来修改您的视图以添加data-validate带有验证URL的属性:

<%= text_field_tag(:user, :'data-validate' => '/users/checkname') %>
Run Code Online (Sandbox Code Playgroud)

下一步添加路线:

resources :users do
  collection do
    get 'checkname'
  end
end
Run Code Online (Sandbox Code Playgroud)

最后一步创建验证:

class UsersController < ApplicationController
  def checkname
    if User.where('user = ?', params[:user]).count == 0
      render :nothing => true, :status => 200
    else
      render :nothing => true, :status => 409
    end
    return
  end

  #... other controller stuff
end
Run Code Online (Sandbox Code Playgroud)


小智 0

为什么不能从 javascript 代码发送 ajax 请求?

最好的方法是在焦点丢失时发送 GET ajax 请求。然后,get 请求可能返回 true 或 false,然后您的 javascript 可以将其反映在页面上。