无法获取包含 javascript 代码的 json 中 php 变量的 return 值

Can't get the return value of the php variable in json which contain javascript code

我正在尝试在我的 php 控制器中创建一个动态 javascript 代码,并希望将其 return 到 UI 即 angular js作为 JSON,但我得到的是 '' 作为响应。

这是我的 php 代码,我想 return 作为 json:

 $user_id = Auth::user()->id;
 $bcamp = Bcamp::where('user_id','=',intval($user_id))->first();//TODO How to clarify which campaign should be showed.
 $bcamp_id = $bcamp->_id;
 $width = $this->request->input('width');
 $height = $this->request->input('height');

 $script  = "<script type='text/javascript'>";
 $script .= "!( function( w, d ) {";
 $script .= "'use strict';";
 $script .= "var ad = { user: '".$user_id."', campaign_id: '".$bcamp_id."', seat_id: '".$seat_id."', width: '".$width."', height: '".$height."', id: 'iranad-' + ~~( Math.random() * 999999  ) },";
 $script .= "h = d.head || d.getElementsByTagName( 'head' )[ 0 ],";
 $script .= "s = location.protocol + '//localhost/banneri/iranad/ia.js';";
 $script .= "if ( typeof w.anetworkParams != 'object' )";
 $script .= "w.anetworkParams = {};";
 $script .= "d.write( '<div id=\"' + ad.id + '\" style=\"display: inline-block\"></div>' );";
 $script .= "w.anetworkParams[ ad.id ] = ad;";
 $script .= "d.write( '<script type=\"text/javascript\" src=' + s + ' async></script>' );";
 $script .= "})( this, document );";
 $script .= "</script>";
 $response = \Response::json($script, $statusCode);
 return $response;

我认为它正在转义脚本。如何解决这个问题?

仅供参考:这是我正在使用的 Laravel 5.3 框架。

$script 不是 json。它是一个字符串。

\Response::json 应该足够聪明来处理它并按原样发送响应,但是如果您期望 json 在客户端,它将无法解析它。

我不明白为什么你需要整个 JS 代码由你的控制器 returned。它几乎是静态的。唯一的动态部分是

{ user: '".$user_id."', campaign_id: '".$bcamp_id."', seat_id: '".$seat_id."', width: '".$width."', height: '".$height."', id: 'iranad-' }", which is valid JSON, unless you mess up with values of the variables, e.g. if it has unescaped quotes.

基本上你需要return的是:

return \Response::json(['user' => $user_id, 'campaign_id' => $bcamp_id ... etc ], $statusCode);

为了 Response 将其转换为有效的 json。响应应加载到客户端的 var ad,并添加连接 ad.idMath.random() * 999999