0
0

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\Response;
  13. class Jsonp extends Response
  14. {
  15. // 输出参数
  16. protected $options = [
  17. 'var_jsonp_handler' => 'callback',
  18. 'default_jsonp_handler' => 'jsonpReturn',
  19. 'json_encode_param' => JSON_UNESCAPED_UNICODE,
  20. ];
  21. protected $contentType = 'application/javascript';
  22. /**
  23. * 处理数据
  24. * @access protected
  25. * @param mixed $data 要处理的数据
  26. * @return mixed
  27. * @throws \Exception
  28. */
  29. protected function output($data)
  30. {
  31. try {
  32. // 返回JSON数据格式到客户端 包含状态信息 [当url_common_param为false时是无法获取到$_GET的数据的,故使用Request来获取<xiaobo.sun@qq.com>]
  33. $var_jsonp_handler = $this->app['request']->param($this->options['var_jsonp_handler'], "");
  34. $handler = !empty($var_jsonp_handler) ? $var_jsonp_handler : $this->options['default_jsonp_handler'];
  35. $data = json_encode($data, $this->options['json_encode_param']);
  36. if (false === $data) {
  37. throw new \InvalidArgumentException(json_last_error_msg());
  38. }
  39. $data = $handler . '(' . $data . ');';
  40. return $data;
  41. } catch (\Exception $e) {
  42. if ($e->getPrevious()) {
  43. throw $e->getPrevious();
  44. }
  45. throw $e;
  46. }
  47. }
  48. }