我想弄清楚我怎么能把它变成这样:
$('#username').blur(function(){
$.post('register/isUsernameAvailable',
{"username":$('#username').val()},
function(data){
if(data.username == "found"){
alert('username already in use');
}
}, 'json');
});
接近这个:
rules: {
username: {
minlength: 6,
maxlength: 12,
remote: {
url: 'register/isUsernameAvailable',
type: 'post',
data: {
'username': $('#username').val()
}
}
}
但是我很难完成它。我想要的是让它显示错误消息而不是警报,但我可以在实际的 jquery 验证消息中设置消息。
http://docs.jquery.com/Plugins/Validation/Methods/remote#options
更新:
出于某种原因,它没有将其作为 POST 执行,而是将其作为 GET 请求执行,但不知道为什么。这是更新的代码:
rules: {
username: {
minlength: 6,
maxlength: 12,
remote: {
url: 'register/isUsernameAvailable',
dataType: 'post',
data: {
'username': $('#username').val()
},
success: function(data) {
if (data.username == 'found')
{
message: {
username: 'The username is already in use!'
}
}
}
}
},
更新 2:
现在我已经到了某个地方,我又回到了获取 POST 请求的地方。我还有两个问题。其中之一是要完成另一个 POST 请求,用户必须刷新表单。最后一个问题是,如果找到返回的用户名,它不会显示错误消息。
rules: {
username: {
minlength: 6,
maxlength: 12,
remote: {
type: 'post',
url: 'register/isUsernameAvailable',
data: {
'username': $('#username').val()
},
dataType: 'json',
success: function(data) {
if (data.username == 'found')
{
message: {
username: 'The username is already in use!'
}
}
}
}
},
更新:
public function isUsernameAvailable()
{
if ($this->usersmodel->isUsernameAvailable($this->input->post('username')))
{
return false;
}
else
{
return true;
}
}
更新 4:
控制器:
public function isUsernameAvailable()
{
if ($this->usersmodel->isUsernameAvailable($this->input->post('username')))
{
return false;
}
else
{
return true;
}
}
public function isEmailAvailable()
{
if ($this->usersmodel->isEmailAvailable($this->input->post('emailAddress')))
{
return false;
}
else
{
return true;
}
}
模型:
/**
* Check if username available for registering
*
* @param string
* @return bool
*/
function isUsernameAvailable($username)
{
$this->db->select('username');
$this->db->where('LOWER(username)=', strtolower($username));
$query = $this->db->get($this->usersTable);
if ($query->num_rows() == 0)
{
return true;
}
else
{
return false;
}
}
/**
* Check if email available for registering
*
* @param string
* @return bool
*/
function isEmailAvailable($email)
{
$this->db->select('email');
$this->db->where('LOWER(email)=', strtolower($email));
$query = $this->db->get($this->usersTable);
if($query->num_rows() == 0)
{
return true;
}
else
{
return false;
}
}