0

我正在尝试从 codeigniter 视图返回 json 数据。但我的代码不起作用。我已经尝试了这个站点中给出的所有选项。但我无法从视图中返回 json 数据,这是控制器代码。

<?php
class Json extends CI_Controller
{

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

    }
    public function index()
    {
        $this->load->model('get_json');
        $data['message']=$this->get_json->get_fruits();

         if ($data!== false)
         {
                    $this->load->view('json',json_encode($data['message']));
        }
    }
}

我的模型

<?php

    class get_json extends CI_Model
    {
        function __construct()
        {
           parent::__construct();
        }


        function get_fruits()
        {
            $sql = "SELECT * FROM fruit where name='Apple'";
            $query = $this->db->query($sql);
            // Fetch the result array from the result object and return it
            return $query->result();

        }

    }

查看代码:

<?php
$this->output->set_content_type('application/json');
echo $message;

请帮我看看我的代码哪里出错了。

这是我在我的日志中得到的:

ERROR - 2012-05-11 15:28:40 --> Severity: Notice  --> Undefined variable: message C:\xampp\htdocs\ci\system\core\Loader.php(829) : eval()'d code 3
DEBUG - 2012-05-11 15:28:40 --> File loaded: application/views/json.php
4

1 回答 1

3

将您的控制器index方法更改为:

public function index()
    {
        $this->load->model('get_json');
        $data['message']= json_encode($this->get_json->get_fruits());

         if ($data!== false)
         {
                    $this->load->view('json',$data);
        }
}

你应该很高兴:你需要将数组传递给$this->load->view,而不是编码值。

编辑:作为旁注,对于这种事情,您甚至不需要视图。您可以直接从控制器返回结果:

public function index()
    {
        $this->load->model('get_json');
        $message = $this->get_json->get_fruits();

         if ($message !== false)
         {
                    $this->output->set_content_type('application/json');
                    echo json_encode($message);
        }
}

更清洁,将所有东西放在一个地方,并且效率更高。

于 2012-05-11T14:38:24.077 回答