无法使用codeigniter中的jQuery的.serialize()通过控制器中的HTTP POST值访问表单值

时间:2012-05-09 07:07:39

标签: codeigniter

我在使用jQuery .serialize()方法发布表单时遇到问题。当表单传递给jQuery函数时,它可以通过HTTP POST获取所有值,但是当使用.serialize()方法将表单发送到控制器时,控制器无法获取值。这是我的代码:

在视图中:

<form id="loginForm" name="loginForm" method="post">
Email: <input type="text" class="contactStyle required email" id="email" name="email"/>
Password:<input type="password" class="contactStyle required" id="password" name="password"/>
</form>
<a href='#' onclick="login(); return false;" class="loginBut" >Login</a>

Javascript代码:

login = function(){
.post(base_url + "elements/ajax_login",  $("#loginForm").serialize(),
function(data){
if(data.success == 'success'){
   top.location =  top.location;
}else if(data.success == 'admin'){
   top.location = base_url + "admin";
}else if(data.success == 'failed'){
          alert('Incorrect login');
          //ADD POPUP
          $('#warn').hide().html('Your email / password combination is not correct.').show('slow');
}else{
    alert("An error has occured please try refreshing the page.")
}
},'json');
}

控制器:

function ajax_login() {
    $email = $this->input->post('email');
    $result = array();

    if ($this->ion_auth->login($email, $this->input->post('password'), 0)) { //if the login is successful
        //if its an admin send them to the dashboard
        if ($this->ion_auth->is_admin()) {
            $result['success'] = 'admin';
        } else {                
            $result['success'] = 'success';
        }
    } else { //if the login was un-successful
        $result['success'] = 'failed';            
    }
    echo json_encode($result);

}

我在第一步中遇到错误,将值从View传递给jQuery是Method Post,但是当将值从jquery传递给controller时,它使用Method Get。

1 个答案:

答案 0 :(得分:1)

尝试改为seralizeArray:

$.post(base_url + "elements/ajax_login",  $("#loginForm").serializeArray(),
function(data){
    // all your stuff
},'json');