jquery验证表(codeigniter)

时间:2012-11-14 03:12:54

标签: jquery codeigniter

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的代码工作正常。

有人可以帮助我吗?

1 个答案:

答案 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);