使用jQuery和Ajax在轨检查用户名可用性 [英] Check username availability using jquery and Ajax in rails
问题描述
我使用的铁轨使用jQuery和Ajax检查用户名的可用性。我在用 下面的jQuery插件验证的目的。
I am using rails with jquery and ajax to check the availability of username. I am using the following plugin for jquery validation purpose.
https://github.com/posabsolute/jQuery-Validation-Engine
在我的控制器中,我使用下面的方法来检查用户名的可用性。
In my controller i am using the following method to check the username availability.
def check_name
name = params[:name]
if name.strip == ""
render :json => { :available => false }
return
end
user = User.find(:first, :conditions => [ "name = ?", name])
if realm
render :json => ["name", false , "This name is already taken"]
else
render :json => ["name", true , ""]
end
end
这是写的方法,正确的方法是什么?我查了很多的用户名可用性 在这个论坛的帖子,但没有解决。
Is this the correct way to write the method? I checked many of the username availability posts in this forum, but nothing worked out.
推荐答案
我添加了答案。抱歉耽搁家伙。
I am adding the answer. Sorry for the delay guys.
信用第一插件:<一href="https://github.com/posabsolute/jQuery-Validation-Engine">https://github.com/posabsolute/jQuery-Validation-Engine 。 在应用程序验证中使用的插件。
First credit to the plugin:https://github.com/posabsolute/jQuery-Validation-Engine . Used the plugin for validations in the application.
在视图中,我有
<%= f.username_field :username, :id => 'free-user', :placeholder=>'User Name', :class => "validate[required, ajax[ajaxUserCall]]", "data-prompt-position" => "topLeft:0,9"%>
在同样的观点,在Java脚本:
In the same view, in java script:
<script type="text/javascript">
$(document).ready(function(){
$("#free-user").bind("jqv.field.result", function(event, field, errorFound, prompText){
if(errorFound){
$(".continue").attr("disabled", false); // .continue is a button
} else{
$(".continue").attr("disabled", true);
}
})
});
</script>
在routes.rb中我有以下途径。
In routes.rb i have the following route.
match '/check-user' =>"users#check_user" // creating route for ajax call
在jquery.validationEngine-en.js文件我有以下:
In jquery.validationEngine-en.js file i have following:
"ajaxUserCall": {
"url": "/check-user",
// you may want to pass extra data on the ajax call
"alertText": "* This user is already taken",
"alertTextLoad": "* Validating, please wait"
},
在用户控制器,我有以下方法
In users controller, i have the following method
def check_user
user = params[:fieldValue]
user = User.where("username = ?", username).first
if user.present?
render :json => ["free-user", false , "This User is already taken"]
else
render :json => ["free-user", true , ""]
end
end
这篇关于使用jQuery和Ajax在轨检查用户名可用性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!