Usage:
1 2 3 4 5 6 7 8 9 |
require_once APPPATH.'traits/AjaxResponse.php'; class CustomerList extends CI_Controller { use AjaxResponse; public function __construct(){ } } |
Trait
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
trait AjaxResponse { protected $is_laravel = false; protected function json_response($data){ if($this->is_laravel == false){ header('Content-Type: application/json'); echo json_encode($data); exit(); }else{ return response()->json($data); } } protected function success_response($data, $extra=null){ $response = [ 'status' => 'success', 'data' => $data, 'extra' => $extra ]; if($this->is_laravel == false){ header('Content-Type: application/json'); echo json_encode($response); exit(); }else{ return response()->json($response); } } protected function fail_response($msg, $code=0){ $response = [ 'status' => 'fail', 'code' => $code, 'message' => $msg ]; if($this->is_laravel == false){ header('Content-Type: application/json'); echo json_encode($response); exit(); }else{ return response()->json($response); } } protected function error_response($errors, $msg='網路錯誤'){ $response = [ 'message' => $msg, 'errors' => $errors ]; if($this->is_laravel == false){ header('Content-Type: application/json'); echo json_encode($response); exit(); }else{ return response()->json($response, 422); } } protected function datatable_response($total, $filtered_total, $data=[], $draw=0){ $out = array(); $out['draw'] = $draw; $out['recordsTotal'] = $total; $out['recordsFiltered'] = $filtered_total; $out['data'] = $data; if($this->is_laravel == false){ header('Content-Type: application/json'); echo json_encode($out); exit(); }else{ return response()->json($out); } } } |