在ThinkPHP中,可以使用json
方法返回JSON数据。
方法一:使用json
方法返回JSON数据
// 控制器方法中返回JSON数据 public function index() { $data = https://www.yisu.com/ask/['name' => 'John', 'age' => 25]; return json($data); }
方法二:使用JsonResponse
类返回JSON数据
// 控制器方法中返回JSON数据 public function index() { $data = https://www.yisu.com/ask/['name' => 'John', 'age' => 25]; return new \think\response\Json($data); }
以上两种方法都可以将数组或对象转换为JSON格式的数据,并返回给前端。
注意:在使用json
方法时,需要在控制器类中先引入use think\response\Json;
。