Api.php 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. <?php
  2. namespace app\api\controller;
  3. use think\Controller;
  4. /**
  5. * 接口父类
  6. */
  7. class Api extends Controller{
  8. protected function _initialize(){
  9. $this->header();
  10. $this->init();
  11. }
  12. protected function header(){
  13. header('Access-Control-Allow-Origin:*');
  14. header('Content-type: application/json;chartset=uft-8');
  15. if( $_SERVER['REQUEST_METHOD'] == 'OPTIONS'){
  16. exit;
  17. }
  18. }
  19. protected function init(){
  20. }
  21. public function output($code,$msg,$data = [],$count = 0){
  22. try {
  23. // 返回JSON数据格式到客户端 包含状态信息
  24. $count = $count == 0?count($data):$count;
  25. $data = json_encode(['code'=>$code,'msg'=>$msg,'data'=>$data,'count'=>$count], JSON_UNESCAPED_UNICODE);
  26. if ($data === false) {
  27. throw new \InvalidArgumentException(json_last_error_msg());
  28. }
  29. header('Content-type: application/json');
  30. echo $data;exit();
  31. } catch (\Exception $e) {
  32. if ($e->getPrevious()) {
  33. throw $e->getPrevious();
  34. }
  35. throw $e;
  36. }
  37. }
  38. }