【问题标题】:How do I replace front-end views with JSONs in Codeigniter 3?如何在 Codeigniter 3 中用 JSON 替换前端视图?
【发布时间】:2019-08-15 14:07:24
【问题描述】:

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

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

我想如果我可以用 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');
    }


    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。

最好的方法是什么?

【问题讨论】:

  • 您仍然需要一个视图来加载 js 和足够的 DOM 以供前端技术使用。您仍然需要控制器和方法作为 URL 提供给您的前端 - 不是吗?。

标签: php codeigniter


【解决方案1】:

您是否尝试过使用原生 php 对其进行简单编码?或者这里有什么问题?

我会这样做:

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

所以你可以在视图中使用 $json。

... 最终 JSON.parse 在 JS 前端。

【讨论】:

  • 我必须在至少两个控制器每种方法中使用它,我宁愿不这样做。
【解决方案2】:

在控制器中创建一个方法来回显 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-&gt;json 数组:

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

然后渲染:

$this->render_json();

顺便说一句,如果您想在全局范围内使用它,只需将其移至基本控制器即可。


示例

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

现在,当您通过 ajax 调用此方法时,它会为您提供一个 json 对象,其中包含 $this-&gt;json 数组中的任何内容,在 js 中:

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

【讨论】:

  • 我没有基本控制器
  • 应该将$this-&gt;render_json(); 放在/视图中吗?
  • 无论如何,您都应该创建一个基本控制器以消除冗余并使其保持干燥......对于$this-&gt;render_json();,将其放在您方法的末尾,它可以回显结果。
  • @RazvanZamfir .. 看到编辑,我希望它现在清楚了!
  • 在我的 Posts 控制器的上下文中,您将如何将 帖子列表 租用为 JSON?
【解决方案3】:

我在控制器的每个方法中都使用了这行代码,而不是渲染视图

$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));

    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-02
    • 1970-01-01
    • 2011-04-18
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多