JS:
$(document).ready(function(){
$('#username').change(function(){
var username = $('#username').val();
$('#usernamemsg').html('<img src="<?php echo base_url()?>images/ajax_loader.gif"/> Checking');
$.ajax({
type: "POST",
url: "<?php echo base_url()?>user/username_validation",
dataType: "json",
data: "username="+username,
success: function(data){
if(data.valid){
$('#usernamemsg').html(data.msg);
}else{
$('#usernamemsg').html(data.msg);
}
}
});
});
});
查看:
<form id="add" method="post" action="">
<table>
<tr>
<td>Username</td>
<td><input type="text" id="username" name="username" />
<div id="usernamemsg"></div></td></tr>
<tr>
<td>Password</td>
<td><input type="password" id="password" name="password" /></td></tr>
<tr>
<td><input type="submit" name="add" value="OK" id="submit" /></td></tr>
</table></form>
控制器:
public function index(){
$data['title'] = 'Register';
$data['template'] = 'outside/validation/validation';
$this->load->view('templates/home_template',$data);
$add = $this->input->post('add');
if($add){
$data = array(
'username' => trim($this->input->post('username')),
'password' => trim($this->input->post('password')));
$this->data_mod->insert('user',$data);
redirect('registration/welcome');
}
}
public function username_validation(){
$user = $this->data_mod->validation('user',array('username' => $this->input->post('username')));
if($user >= 1){
$msg = array(
'valid' => false,
'msg' => 'Username is already taken');
}else{
$msg = array(
'valid' => true,
'msg' => 'Username is available');
}
echo json_encode($msg);
}
* 我正在努力学习英语,所以我说得不好。
当我按提交时,表单不会通知用户名字段,并且当我输入用户名时,它提交给服务器,而js的代码工作正常。
有人可以帮助我吗?
答案 0 :(得分:1)
然后在js
var username = $('#username').val();
if($.trim(username).length==0)
{
alert('Please enter user name !');
return false;
}
在关注行
之前$('#usernamemsg').html('<img src="<?php echo base_url()?>images/ajax_loader.gif"/> Checking');
以及success
回拨替换
if(data.valid){
$('#usernamemsg').html(data.msg);
}else{
$('#usernamemsg').html(data.msg);
}
与
$('#usernamemsg').html(data.msg);