Jsonp.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. namespace think\response;
  12. use think\Request;
  13. use think\Response;
  14. class Jsonp extends Response
  15. {
  16. // 输出参数
  17. protected $options = [
  18. 'var_jsonp_handler' => 'callback',
  19. 'default_jsonp_handler' => 'jsonpReturn',
  20. 'json_encode_param' => JSON_UNESCAPED_UNICODE,
  21. ];
  22. protected $contentType = 'application/javascript';
  23. /**
  24. * 处理数据
  25. * @access protected
  26. * @param mixed $data 要处理的数据
  27. * @return mixed
  28. * @throws \Exception
  29. */
  30. protected function output($data)
  31. {
  32. try {
  33. // 返回JSON数据格式到客户端 包含状态信息 [当url_common_param为false时是无法获取到$_GET的数据的,故使用Request来获取<xiaobo.sun@qq.com>]
  34. $var_jsonp_handler = Request::instance()->param($this->options['var_jsonp_handler'], "");
  35. $handler = !empty($var_jsonp_handler) ? $var_jsonp_handler : $this->options['default_jsonp_handler'];
  36. $data = json_encode($data, $this->options['json_encode_param']);
  37. if ($data === false) {
  38. throw new \InvalidArgumentException(json_last_error_msg());
  39. }
  40. $data = $handler . '(' . $data . ');';
  41. return $data;
  42. } catch (\Exception $e) {
  43. if ($e->getPrevious()) {
  44. throw $e->getPrevious();
  45. }
  46. throw $e;
  47. }
  48. }
  49. }