簡體   English   中英

如何在Codeigniter 3中用JSON替換前端視圖?

[英]How do I replace front-end views with JSONs in Codeigniter 3?

我正在使用Codeigniter 3.1.8開發 博客應用程序

目前,它的管理區域與前端已完全分開。 后端 (管理區域)和前端都使用“經典” Codeigniter視圖顯示數據。

我認為,如果可以用JSONS替換前端的經典視圖這樣可以獨立於經典的Codeigniter視圖而使用Vue或Angular等前端技術來格式化和顯示它們,那將是很棒的,而我只能在后端使用。

JSONS應該直接從涉及帖子和單個帖子頁面功能的控制器中刪除, 而無需使用views

我需要一個可靠的方法,因為控制器非常復雜。 這是Posts控制器:

class Posts extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
    }

    private function _initPagination($path, $totalRows, $query_string_segment = 'page') {
    //load and configure pagination 
        $this->load->library('pagination');
        $config['base_url'] = base_url($path);
        $config['query_string_segment'] = $query_string_segment; 
        $config['enable_query_strings'] =TRUE;
        $config['reuse_query_string'] =TRUE;
        $config['total_rows'] = $totalRows;
        $config['per_page'] = 12;
        if (!isset($_GET[$config['query_string_segment']]) || $_GET[$config['query_string_segment']] < 1) {
            $_GET[$config['query_string_segment']] = 1;
        }
        $this->pagination->initialize($config);

        $limit = $config['per_page'];
        $offset = ($this->input->get($config['query_string_segment']) - 1) * $limit;

        return ['limit' => $limit, 'offset' => $offset];
    }

    public function index() {

    //call initialization method
        $config = $this->_initPagination("/", $this->Posts_model->get_num_rows());

        $data = $this->Static_model->get_static_data();
        $data['pages'] = $this->Pages_model->get_pages();
        $data['categories'] = $this->Categories_model->get_categories();  

        //use limit and offset returned by _initPaginator method
        $data['posts'] = $this->Posts_model->get_posts($config['limit'], $config['offset']);
        $this->load->view('partials/header', $data);
        $this->load->view('posts');
        $this->load->view('partials/footer');
    }


    public function byauthor($authorid){
        $data = $this->Static_model->get_static_data();
        $data['pages'] = $this->Pages_model->get_pages();
        $data['categories'] = $this->Categories_model->get_categories(); 
        $data['posts'] = $this->Posts_model->get_posts_by_author($authorid); 
        $data['posts_count'] = $this->Posts_model->posts_by_author_count($authorid); 
        $data['posts_author'] = $this->Posts_model->posts_author($authorid);

        $this->load->view('partials/header', $data);
        $this->load->view('posts_by_author');
        $this->load->view('partials/footer');
    }

    public function post($slug) {
        $data = $this->Static_model->get_static_data();
        $data['pages'] = $this->Pages_model->get_pages();
        $data['categories'] = $this->Categories_model->get_categories();
        $data['posts'] = $this->Posts_model->sidebar_posts($limit=5, $offset=0);
        $data['post'] = $this->Posts_model->get_post($slug);

        if ($data['categories']) {
            foreach ($data['categories'] as &$category) {
                $category->posts_count = $this->Posts_model->count_posts_in_category($category->id);
            }
        }

        if (!empty($data['post'])) {
            // Overwrite the default tagline with the post title
            $data['tagline'] = $data['post']->title;

            // Get post comments
            $post_id = $data['post']->id;
            $data['comments'] = $this->Comments_model->get_comments($post_id);

            $this->load->view('partials/header', $data);
            $this->load->view('post');
        } else {
            $data['tagline'] = "Page not found";
            $this->load->view('partials/header', $data);
            $this->load->view('404');
        }
        $this->load->view('partials/footer');
    }

}

因此,我需要一個堅如磐石的方法來一次性將所有內容作為JSON吐出。

最好的方法是什么?

您是否嘗試過使用本地php對其進行簡單編碼? 還是這里的問題是什么?

我會這樣做:

$data['json']=json_encode($data);

因此您可以在視圖中使用$ json。

…然后是JS前端中的JSON.parse。

在控制器中創建用於回顯json輸出的方法

public $json = array();

public function render_json()
{
    $this->output
    ->set_status_header(200)
    ->set_content_type('application/json')
    ->set_output(json_encode( $this->json ));
}

並在控制器內部的任何方法中都追加到$this->json數組:

$this->json['key'] = 'value';

然后渲染:

$this->render_json();

順便說一句,如果您想在全球范圍內使用它,只需將其移至基本控制器即可。


public function fetch()
{
    $this->json['key'] = 'value';
    $this->render_json();
}

現在,當您通過ajax調用此方法時,它將為您提供一個JSON對象,其中包含js中$this->json數組中的內容:

.done(function( response ) {
    console.log(response.key); // = value
});

我在控制器的每個方法中都使用了以下代碼, 而不是呈現視圖

$this->output->set_content_type('application/json')->set_output(json_encode($data));

這就是控制器現在的樣子:

class Posts extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
    }

    private function _initPagination($path, $totalRows, $query_string_segment = 'page') {
    //load and configure pagination 
        $this->load->library('pagination');
        $config['base_url'] = base_url($path);
        $config['query_string_segment'] = $query_string_segment; 
        $config['enable_query_strings'] =TRUE;
        $config['reuse_query_string'] =TRUE;
        $config['total_rows'] = $totalRows;
        $config['per_page'] = 12;
        if (!isset($_GET[$config['query_string_segment']]) || $_GET[$config['query_string_segment']] < 1) {
            $_GET[$config['query_string_segment']] = 1;
        }
        $this->pagination->initialize($config);

        $limit = $config['per_page'];
        $offset = ($this->input->get($config['query_string_segment']) - 1) * $limit;

        return ['limit' => $limit, 'offset' => $offset];
    }

    public function index() {

    //call initialization method
        $config = $this->_initPagination("/", $this->Posts_model->get_num_rows());

        $data = $this->Static_model->get_static_data();
        $data['pages'] = $this->Pages_model->get_pages();
        $data['categories'] = $this->Categories_model->get_categories();  

        //use limit and offset returned by _initPaginator method
        $data['posts'] = $this->Posts_model->get_posts($config['limit'], $config['offset']);

         $this->output->set_content_type('application/json')->set_output(json_encode($data));
    }

    public function byauthor($authorid){
        $data = $this->Static_model->get_static_data();
        $data['pages'] = $this->Pages_model->get_pages();
        $data['categories'] = $this->Categories_model->get_categories(); 
        $data['posts'] = $this->Posts_model->get_posts_by_author($authorid); 
        $data['posts_count'] = $this->Posts_model->posts_by_author_count($authorid); 
        $data['posts_author'] = $this->Posts_model->posts_author($authorid);

        $this->output->set_content_type('application/json')->set_output(json_encode($data));
    }

    public function post($slug) {
        $data = $this->Static_model->get_static_data();
        $data['pages'] = $this->Pages_model->get_pages();
        $data['categories'] = $this->Categories_model->get_categories();
        $data['posts'] = $this->Posts_model->sidebar_posts($limit=5, $offset=0);
        $data['post'] = $this->Posts_model->get_post($slug);

        if ($data['categories']) {
            foreach ($data['categories'] as &$category) {
                $category->posts_count = $this->Posts_model->count_posts_in_category($category->id);
            }
        }

        if (!empty($data['post'])) {
            // Overwrite the default tagline with the post title
            $data['tagline'] = $data['post']->title;

            // Get post comments
            $post_id = $data['post']->id;
            $data['comments'] = $this->Comments_model->get_comments($post_id);

             $this->output->set_content_type('application/json')->set_output(json_encode($data));
        } else {
            $data['tagline'] = "Page not found";
             $this->output->set_content_type('application/json')->set_output(json_encode($data));
        }
         $this->output->set_content_type('application/json')->set_output(json_encode($data));

    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM