dongqiang8683 2014-11-17 07:05
浏览 49
已采纳

使用ajax和不使用ajax的Codeigniter-控制器视图

I have a default controller:

class Home extends CI_Controller {

public function index() 
{   
    $data['content']='discover';
    $this->load->view('layouts/master', $data);             
}   

public function categories()
{
    $this->load->view('categories');
}

}

On click, using AJAX i was able to load the view categories.php and update the URL to www.mywebsite.com/categories without refreshing the page.

But now, if the user lands here directly using the link or refreshes the page he ends up loading only the categories.php view and not the master.php view

  1. How do i load the master.php and categories.php view on direct URL navigation or page refresh

  2. Just load categories.php when using AJAX.

My AJAX:

$('#navbar a').click(function(e){
    e.preventDefault();
    href=$(this).attr('href');
    if (href.indexOf(document.domain) > -1 || href.indexOf(':') === -1){
        window.history.pushState('obj', '', href);
        navigat(href);          
    }       
});

function navigat(href){             
    $.ajax({
        type:'GET',
        url:href,
        cache:false,
        dataType: 'html',
        statusCode: {
                404: function() {
                  $("#content").html('Could not contact server.');
                },
                500: function() {
                  $("#content").html('A server-side error has occurred.');
                }
        },
        error: function() {
            $("#content").html('A problem has occurred.');
        },
        success: function(html) {
            $('#content').html(html);

        }
    });     
};

Thanks!

  • 写回答

2条回答 默认 最新

  • dongpo5264 2014-11-17 08:46
    关注

    The CodeIgniter Input Class Provides some helper functions to deal with user inputs , this class is initialized automatically by the system so there is no need to do it manually.

    I always recommend to use this class instead using PHP Core Input Variables while dealing with forms and requests.

    To check Ajax Request in CodeIgniter, codeIgniter Output Class Method class is_ajax_request() , this function checks to see if the HTTP_X_REQUESTED_WITH server header has been set, if set response will be true otherwise false means it will returns a boolean response.

    In you controller you can use below code

    if (!$this->input->is_ajax_request()) {
            echo "Not ajax request";
    } else {
            echo "Ajax Request";
    }
    

    Hence using the above script in your controller action you can identify whether user is coming directly or from ajax call.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 操作系统相关算法中while();的含义
  • ¥15 CNVcaller安装后无法找到文件
  • ¥15 visual studio2022中文乱码无法解决
  • ¥15 关于华为5g模块mh5000-31接线问题
  • ¥15 keil L6007U报错
  • ¥15 webapi 发布到iis后无法访问
  • ¥15 初学者如何快速上手学习stm32?
  • ¥15 如何自动更换布娃娃图片上的衣服
  • ¥15 心理学eprime编程
  • ¥15 arduino esp8266开发