最近春燕網(wǎng)絡小哥哥在研究ThinkPHP6.0.0,小哥哥遇到如下的問題,在ThinkPHP6.0.0中,無法設置輸出頭信息,也就是說直接使用header函數(shù),結(jié)果沒效果。在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]];//隨便來一個數(shù)據(jù)
View::assign('json', json_encode($json));#數(shù)據(jù)傳至模板
View::fetch();
}
}上面代碼想將json數(shù)據(jù)傳至模板,再由模板輸出大量js代碼,但上面的代碼輸出的header信息為:
Content-Type: text/html; charset=utf-8
,并不是想要的“text/javascript”,這可把春燕網(wǎng)絡的程序工程師哥哥急壞了。好在經(jīng)小哥哥的努力研究,最終找到了解決方案。ThinkPHP6.0使用header()函數(shù)無效,如何使用response調(diào)用View輸出js代碼?小編就不在這兒不賣關(guān)子了,畢竟不是小編寫的,小編沒那本事,都得感謝程序小哥哥。代碼如下:
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]];//隨便來一個數(shù)據(jù)
$header = ["Content-type"=>"text/javascript"];#設置header頭信息
View::assign('json', json_encode($json));#數(shù)據(jù)傳至模板
$response = Response()::create('js','View')->header($header);
throw new HttpResponseException($response);
}
}經(jīng)如上代碼處理,完美解決了“ThinkPHP6.0使用header()函數(shù)無效,如何使用response調(diào)用View輸出js代碼”的問題。
最后感謝小哥哥!