最近春燕网络小哥哥在研究ThinkPHP6.0.0,小哥哥遇到如下的问题,在ThinkPHP6.0.0中,无法设置输出头信息,也就是说直接使用header函数,结果没效果。在ThinkPHP6.0.0中,下面的代码是无效的。
namespace app\index\controller;
use think\facade\View;
class Js
{
    public function js()
    {
        header('Content-Type: application/x-javascript; charset=utf-8');#此行无效
        $json = ['data'=>[1,2,3]];//随便来一个数据        
        View::assign('json', json_encode($json));#数据传至模板
        View::fetch();
    }
}上面代码想将json数据传至模板,再由模板输出大量js代码,但上面的代码输出的header信息为:
Content-Type: text/html; charset=utf-8
,并不是想要的“text/javascript”,这可把春燕网络的程序工程师哥哥急坏了。好在经小哥哥的努力研究,最终找到了解决方案。ThinkPHP6.0使用header()函数无效,如何使用response调用View输出js代码?小编就不在这儿不卖关子了,毕竟不是小编写的,小编没那本事,都得感谢程序小哥哥。代码如下:
namespace app\admin\controller;
use think\facade\View;
use think\exception\HttpResponseException;
use think\Response;
class Js
{
    public function js()
    {
        $json = ['data'=>[1,2,3]];//随便来一个数据
        $header = ["Content-type"=>"text/javascript"];#设置header头信息
        View::assign('json', json_encode($json));#数据传至模板
        $response = Response()::create('js','View')->header($header);
        throw new HttpResponseException($response);
    }
}经如上代码处理,完美解决了“ThinkPHP6.0使用header()函数无效,如何使用response调用View输出js代码”的问题。
最后感谢小哥哥!