使用Axios Vue:PHP从mysql获取数据有什么问题?

使用Axios Vue:PHP从mysql获取数据有什么问题?,php,vue.js,oop,axios,Php,Vue.js,Oop,Axios,获取数据的方法:我正在尝试使用axios获取数据。但是没有结果,也没有错误 getTodoList() { axios({ method: 'GET', url: 'api/todos.php' }).then(function(res){ console.log(res); }) } 它给了我这个结果: api.todos.php <?php class Todo { private

获取数据的方法:我正在尝试使用
axios
获取数据。但是没有结果,也没有错误

getTodoList() {
    axios({
        method: 'GET',
        url: 'api/todos.php'
    }).then(function(res){
         console.log(res);
    })
}
它给了我这个结果:

api.todos.php

<?php
    class Todo {

        private $connection_string ;

        public function __construct() {
            // connection code. Connection is okay. 
        }

        public function fetchTodo() {
            $sql = "SELECT * FROM todo ";
            $result = mysqli_query($this->connection_string, $sql);
        }
    }

    $todo = new Todo;
    $todo->fetchTodo();
?>


有什么问题,我不明白

我假设您希望API返回JSON数据

从屏幕截图中可以看到,PHP代码当前正在发送(空)HTML响应:
标题:{[…]内容类型:“text/HTML;charset=UTF-8”,[…]}
。这是PHP的默认设置,如果要输出JSON,必须显式发送正确的头

由于您的函数名为
fetchTodo()
,我将只让它获取数据并将其作为JSON输出到其他地方

<?php
    class Todo {

        private $connection_string ;

        public function __construct() {
            // connection code. Connection is okay. 
        }

        public function fetchTodo() {
            $sql = "SELECT * FROM todo ";
            $result = mysqli_query($this->connection_string, $sql);

            // add this line
            return $result ? $result->fetch_all(MYSQLI_ASSOC) : [];
        }
    }

    // tell whoever requested this API that we're going to send JSON data
    header("Content-Type: application/json");

    $todo = new Todo;

    // output whatever fetchTodo() returns as JSON
    echo json_encode($todo->fetchTodo());
?>

嗯,
fetchTodo()
执行一个查询,并假设它工作,将一个结果对象存储在
$result
中。就这样。您没有告诉它做任何其他事情,比如实际输出数据。是的。你完全正确。那我该怎么办?如何将其传递给数组?