1. <?php
  2. function outJsonp($data=null, $result=0, $message='ok', $exit=true, $ext=array(), $ts=true)
  3. {
  4. if (isset($_POST['callback'])) {
  5. outputJs($result, $message, $data, $exit, $ts);
  6. return;
  7. }
  8. header("Content-Type:text/html; charset=utf-8");
  9. $arr = array(
  10. 'result'=>$result,
  11. 'message'=>$message,
  12. 'data'=> ( (is_array($data) && $data) ? $data : null),
  13. );
  14. if ($ts) {
  15. $arr['timestamp'] = time();
  16. }
  17. if(is_array($ext) && $ext){
  18. $arr = array_merge($arr, $ext);
  19. }
  20. if(isset($_GET['debug'])){
  21. print_r($arr);
  22. }
  23. $json = json_encode($arr,JSON_UNESCAPED_UNICODE);
  24. // 如果是 jsonp
  25. if(isset($_GET['callback'])){
  26. echo sprintf("%s(%s);", $_GET['callback'], $json);
  27. }else{
  28. echo $json;
  29. }
  30. if($exit){
  31. exit;
  32. }
  33. }
  34. /**
  35. * 输出js回调
  36. *
  37. * @param int $result
  38. * @param string $message
  39. * @param array $data
  40. * @param bool $exit
  41. */
  42. function outputJs($result, $message, $data=null, $exit=true, $ts = true)
  43. {
  44. if ($ts) {
  45. $arr= array('result'=>$result, 'message'=>$message, 'data'=>$data, 'timestamp'=> time());
  46. } else {
  47. $arr = array('result'=>$result, 'message'=>$message, 'data'=>$data);
  48. }
  49. $json = json_encode($arr);
  50. $js = '<script>';
  51. $js .= 'document.domain = "xunlei.com";';
  52. $js .= sprintf('parent.%s(%s);',$_POST['callback'], $json);
  53. $js .= '</script>';
  54. echo $js;
  55. if($exit){
  56. exit;
  57. }
  58. }
  59. $_POST['callback'] = 'yourCallback';
  60. //$_GET['callback'] = 'yourCallback';
  61. outJsonp(null, 0, 'ok');

分类: web

标签:   jsonp