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 |
<?php namespace App\Traits; // To set $locale value of a model and translate all translatable attributes trait AjaxResponse { protected function success_response($data, $extra=null){ $response = [ 'status' => 'success', 'data' => $data, 'extra' => $extra ]; //header('Content-Type: application/json'); //echo json_encode($response); //exit(); return response()->json($response); } protected function fail_response($msg, $code=0){ $response = [ 'status' => 'fail', 'code' => $code, 'message' => $msg ]; //header('Content-Type: application/json'); //echo json_encode($response); //exit(); return response()->json($response); } protected function error_response($errors, $msg='網路錯誤'){ $response = [ 'message' => $msg, 'errors' => $errors ]; 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; return response()->json($out); } } |
Javascript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
$.ajax({ type: 'post', url: base_url + 'member/signup_save', data: params, dataType: 'json', success: function(data){ if(typeof data.status == 'undefined'){ alert(data); }else if(data.status == 'fail'){ alert(data.message); }else{ //console.log(data); alert('新增成功'); } }, error: function(data){ var errors = data.responseJSON; show_response_error(errors); } }); |