chengkun
2025-06-05 4080b5997b38ca84b3b203c7101dcadb97b76925
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2025 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
declare(strict_types=1);
 
namespace think\response;
 
use think\Cookie;
use think\Request;
use think\Response;
 
/**
 * Jsonp Response
 */
class Jsonp extends Response
{
    // 输出参数
    protected $options = [
        'var_jsonp_handler'     => 'callback',
        'default_jsonp_handler' => 'jsonpReturn',
        'json_encode_param'     => JSON_UNESCAPED_UNICODE,
    ];
 
    protected $contentType = 'application/javascript';
 
    protected $request;
 
    public function __construct(Cookie $cookie, Request $request, $data = '', int $code = 200)
    {
        $this->init($data, $code);
 
        $this->cookie  = $cookie;
        $this->request = $request;
    }
 
    /**
     * 处理数据
     * @access protected
     * @param  mixed $data 要处理的数据
     * @return string
     * @throws \Exception
     */
    protected function output($data): string
    {
        try {
            // 返回JSON数据格式到客户端 包含状态信息 [当url_common_param为false时是无法获取到$_GET的数据的,故使用Request来获取<xiaobo.sun@qq.com>]
            $varJsonpHandler = $this->request->param($this->options['var_jsonp_handler'], "");
            $handler         = !empty($varJsonpHandler) ? $varJsonpHandler : $this->options['default_jsonp_handler'];
 
            $data = json_encode($data, $this->options['json_encode_param']);
 
            if (false === $data) {
                throw new \InvalidArgumentException(json_last_error_msg());
            }
 
            $data = $handler . '(' . $data . ');';
 
            return $data;
        } catch (\Exception $e) {
            if ($e->getPrevious()) {
                throw $e->getPrevious();
            }
            throw $e;
        }
    }
}