如何在 Codeigniter 3 中用 JSON 替换前端视图?

我正在使用Codeigniter 3.1.8开发一个博客应用程序。


目前,它的管理区域与前端很好地分开。两个后端(管理区域)和前端用“经典”笨视图的显示器数据。


我认为,如果我可以用JSONS替换前端的经典视图,那么它们就可以使用Vue 或 Angular 等前端技术进行格式化和显示,而独立于经典的 Codeigniter 视图,我只会在后端使用这些视图。


JSONS 应该直接从参与帖子和单个帖子页面功能的控制器中输出,而无需视图的帮助。


我需要一个可靠的方法,因为控制器非常复杂。这是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');

    }


所以,我需要一种坚如磐石的方法来一次性将所有这些都吐出为 JSON。


最好的方法是什么?


HUWWW
浏览 173回答 3
3回答

冉冉说

在您的控制器中创建一个方法来回显 json 输出public $json = array();public function render_json(){&nbsp; &nbsp; $this->output&nbsp; &nbsp; ->set_status_header(200)&nbsp; &nbsp; ->set_content_type('application/json')&nbsp; &nbsp; ->set_output(json_encode( $this->json ));}并且在您的控制器内的任何方法中只需附加到$this->json数组:$this->json['key'] = 'value';然后渲染:$this->render_json();顺便说一句,如果您想在全球范围内使用它,只需将其移动到基本控制器即可。例子public function fetch(){&nbsp; &nbsp; $this->json['key'] = 'value';&nbsp; &nbsp; $this->render_json();}现在,当您通过 ajax 调用此方法时,它将为您提供一个 json 对象,其中包含$this->json数组中的任何内容,在 js 中:.done(function( response ) {&nbsp; &nbsp; console.log(response.key); // = value});

富国沪深

您是否尝试过使用本机 php 对其进行简单编码?或者这里有什么问题?我会这样做:$data['json']=json_encode($data);所以你可以在视图中使用 $json 。...然后最终在 JS 前端使用 JSON.parse。

阿波罗的战车

我在控制器的每个方法中都使用了这行代码,而不是渲染视图:$this->output->set_content_type('application/json')->set_output(json_encode($data));这是控制器现在的样子:class Posts extends CI_Controller {&nbsp; &nbsp; public function __construct()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; parent::__construct();&nbsp; &nbsp; }&nbsp; &nbsp; private function _initPagination($path, $totalRows, $query_string_segment = 'page') {&nbsp; &nbsp; //load and configure pagination&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; $this->load->library('pagination');&nbsp; &nbsp; &nbsp; &nbsp; $config['base_url'] = base_url($path);&nbsp; &nbsp; &nbsp; &nbsp; $config['query_string_segment'] = $query_string_segment;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; $config['enable_query_strings'] =TRUE;&nbsp; &nbsp; &nbsp; &nbsp; $config['reuse_query_string'] =TRUE;&nbsp; &nbsp; &nbsp; &nbsp; $config['total_rows'] = $totalRows;&nbsp; &nbsp; &nbsp; &nbsp; $config['per_page'] = 12;&nbsp; &nbsp; &nbsp; &nbsp; if (!isset($_GET[$config['query_string_segment']]) || $_GET[$config['query_string_segment']] < 1) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $_GET[$config['query_string_segment']] = 1;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; $this->pagination->initialize($config);&nbsp; &nbsp; &nbsp; &nbsp; $limit = $config['per_page'];&nbsp; &nbsp; &nbsp; &nbsp; $offset = ($this->input->get($config['query_string_segment']) - 1) * $limit;&nbsp; &nbsp; &nbsp; &nbsp; return ['limit' => $limit, 'offset' => $offset];&nbsp; &nbsp; }&nbsp; &nbsp; public function index() {&nbsp; &nbsp; //call initialization method&nbsp; &nbsp; &nbsp; &nbsp; $config = $this->_initPagination("/", $this->Posts_model->get_num_rows());&nbsp; &nbsp; &nbsp; &nbsp; $data = $this->Static_model->get_static_data();&nbsp; &nbsp; &nbsp; &nbsp; $data['pages'] = $this->Pages_model->get_pages();&nbsp; &nbsp; &nbsp; &nbsp; $data['categories'] = $this->Categories_model->get_categories();&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; //use limit and offset returned by _initPaginator method&nbsp; &nbsp; &nbsp; &nbsp; $data['posts'] = $this->Posts_model->get_posts($config['limit'], $config['offset']);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$this->output->set_content_type('application/json')->set_output(json_encode($data));&nbsp; &nbsp; }&nbsp; &nbsp; public function byauthor($authorid){&nbsp; &nbsp; &nbsp; &nbsp; $data = $this->Static_model->get_static_data();&nbsp; &nbsp; &nbsp; &nbsp; $data['pages'] = $this->Pages_model->get_pages();&nbsp; &nbsp; &nbsp; &nbsp; $data['categories'] = $this->Categories_model->get_categories();&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; $data['posts'] = $this->Posts_model->get_posts_by_author($authorid);&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; $data['posts_count'] = $this->Posts_model->posts_by_author_count($authorid);&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; $data['posts_author'] = $this->Posts_model->posts_author($authorid);&nbsp; &nbsp; &nbsp; &nbsp; $this->output->set_content_type('application/json')->set_output(json_encode($data));&nbsp; &nbsp; }&nbsp; &nbsp; public function post($slug) {&nbsp; &nbsp; &nbsp; &nbsp; $data = $this->Static_model->get_static_data();&nbsp; &nbsp; &nbsp; &nbsp; $data['pages'] = $this->Pages_model->get_pages();&nbsp; &nbsp; &nbsp; &nbsp; $data['categories'] = $this->Categories_model->get_categories();&nbsp; &nbsp; &nbsp; &nbsp; $data['posts'] = $this->Posts_model->sidebar_posts($limit=5, $offset=0);&nbsp; &nbsp; &nbsp; &nbsp; $data['post'] = $this->Posts_model->get_post($slug);&nbsp; &nbsp; &nbsp; &nbsp; if ($data['categories']) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; foreach ($data['categories'] as &$category) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $category->posts_count = $this->Posts_model->count_posts_in_category($category->id);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (!empty($data['post'])) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Overwrite the default tagline with the post title&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $data['tagline'] = $data['post']->title;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Get post comments&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $post_id = $data['post']->id;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $data['comments'] = $this->Comments_model->get_comments($post_id);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$this->output->set_content_type('application/json')->set_output(json_encode($data));&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $data['tagline'] = "Page not found";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$this->output->set_content_type('application/json')->set_output(json_encode($data));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$this->output->set_content_type('application/json')->set_output(json_encode($data));&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP