Codeigniter:Ion Auth的Ajax登录重定向问题

时间:2013-07-21 16:33:39

标签: php jquery ajax codeigniter ion-auth

我正在尝试将Ion Auth框架与我的CodeIgniter应用程序一起使用。
当用户单击链接请求时,将转到Controller方法并检查用户是否已登录。如果没有,则重定向到auth\login方法。但是我在success(msg):alert(msg);中获得了登录页面的html Ajax请求

$('img').click(function() {
            $.ajax({
              url: "<?php echo site_url('gallery/openProductDetail');?>",
              type: 'POST',
              success: function(msg) {
                alert(msg);
              }
             });     
      });

控制器

function openProductDetail()
    {
        if (!$this->ion_auth->logged_in())
        {
            redirect('auth/login');
        } else {

            $this->load->view('modal/productdetail');
        }
    }

登录页面这是来自原始Ion Auth的login.pho

<h1><?php echo lang('login_heading');?></h1>
<p><?php echo lang('login_subheading');?></p>

<div id="infoMessage"><?php echo $message;?></div>

<?php echo form_open("auth/login");?>

  <p>
    <?php echo lang('login_identity_label', 'identity');?>
    <?php echo form_input($identity);?>
  </p>

  <p>
    <?php echo lang('login_password_label', 'password');?>
    <?php echo form_input($password);?>
  </p>

  <p>
    <?php echo lang('login_remember_label', 'remember');?>
    <?php echo form_checkbox('remember', '1', FALSE, 'id="remember"');?>
  </p>


  <p><?php echo form_submit('submit', lang('login_submit_btn'));?></p>

<?php echo form_close();?>

<p><a href="forgot_password"><?php echo lang('login_forgot_password');?></a></p>

1 个答案:

答案 0 :(得分:3)

$ret; // declare a variable to return.
if (!$this->ion_auth->logged_in()){
    if($this->input->is_ajax_request()){
        /* This is an AJAX request, send the url back to be redirected to. */
        $ret['url'] = site_url().'auth/login';
        $ret['html'] = FALSE;
    }else{
        /* This is not ajax, it is a standard form submission, let codeigniter handle it*/
        redirect('auth/login');
    }
} else {
    if($this->input->is_ajax_request()){
        $ret['url'] = FALSE; //they are logged in, and this is ajax, don't redirect.
        $ret['html'] = $this->load->view('modal/productdetail', '', TRUE); //allow the HTML to be returned to the server
    }else{
        /* They are logged in, but this is not ajax, redirect them. */
        redirect('modal/productdetail');
    }
}    
echo json_encode($ret); //json_encode our $ret array, and send to browser

通过上述内容,我们创建了一个名为$ret的变量,该变量在执行ajax请求时保存对某些数据的引用。否则,当不使用ajax(没有javascript)时,会产生标准的表单重定向行为。

现在,在我们的成功函数中,我们将检查是否存在data.urldata.html属性,并采取相应的行动。

dataType: 'json', //add this so the success: knows how to parse returned data
success:function(data){
    if(data.url){
        window.location = data.url;
    }else if(data.html){
        $('element').html(data.html); // where "element" is an HTML element on your page you wish to override with a partial view
    }
}