我正在尝试在我的 php Controller 中创建动态 JavaScript 代码,并希望将其返回到 UI,该 UI 是 Angular JS 作为 JSON,但我得到的是 ''
响应。
这是我的 php 代码,我想将其作为 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,它将无法解析它。
我不明白为什么你需要 Controller 返回整个 JS 代码。它几乎是静态的。唯一的动态部分是
{ 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 \Response::json(['user' => $user_id, 'campaign_id' => $bcamp_id ... etc ], $statusCode);
用于 Response
将其转换为有效的 json。响应应加载到客户端的 var ad
中,并将 ad.id
与 Math.random() * 999999
连接起来。
关于javascript - 无法获取包含javascript代码的json中php变量的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40973192/