0

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

$('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>
4

1 回答 1

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
    }
}
于 2013-07-21T16:52:17.140 回答