1. <?php
  2. class My_APIController extends CI_Controller
  3. {
  4. /**
  5. * 公共信息初始化
  6. *
  7. * @param boolean $auth 是否验证
  8. */
  9. public function init()
  10. {
  11. parent::__construct();
  12. }
  13. /**
  14. * 输出 json/jsonp 供 ajax 调用
  15. *
  16. * @param int $result 状态码
  17. * @param string $message 消息
  18. * @param array $data 数据
  19. * @param bool $exit
  20. * @param array $ext
  21. */
  22. protected function outJsonp($data=null, $result=0, $message='ok', $exit=true, $ext=array(), $ts=true)
  23. {
  24. if (isset($_POST['callback'])) {
  25. $this->outputJs($result, $message, $data, $exit, $ts);
  26. return;
  27. }
  28. header("Content-Type:text/html; charset=utf-8");
  29. $arr = array(
  30. 'result'=>$result,
  31. 'message'=>$message,
  32. 'data'=> ( (is_array($data) && $data) ? $data : null),
  33. );
  34. if ($ts) {
  35. $arr['timestamp'] = time();
  36. }
  37. if(is_array($ext) && $ext){
  38. $arr = array_merge($arr, $ext);
  39. }
  40. if(isset($_GET['debug'])){
  41. print_r($arr);
  42. }
  43. $json = json_encode($arr,JSON_UNESCAPED_UNICODE);
  44. // 如果是 jsonp
  45. if(isset($_GET['callback'])){
  46. echo sprintf("%s(%s);", $_GET['callback'], $json);
  47. }else{
  48. echo $json;
  49. }
  50. if($exit){
  51. exit;
  52. }
  53. }
  54. /**
  55. * 输出js回调
  56. *
  57. * @param int $result
  58. * @param string $message
  59. * @param array $data
  60. * @param bool $exit
  61. */
  62. protected function outputJs($result, $message, $data=null, $exit=true, $ts = true)
  63. {
  64. if ($ts) {
  65. $arr= array('result'=>$result, 'message'=>$message, 'data'=>$data, 'timestamp'=> time());
  66. } else {
  67. $arr = array('result'=>$result, 'message'=>$message, 'data'=>$data);
  68. }
  69. $json = json_encode($arr);
  70. $js = '<script>';
  71. $js .= 'document.domain = "shaohualee.com";';
  72. $js .= sprintf('parent.%s(%s);',$_POST['callback'], $json);
  73. $js .= '</script>';
  74. echo $js;
  75. if($exit){
  76. exit;
  77. }
  78. }
  79. }

分类: web

标签:   jsonp