所以这里有很多关于这个的问题,我尝试了很多但没有成功。我正在尝试将一个 php 变量添加到一个 javascript 变量,然后将其放入 json 中。<?php $symbol_json = $row['symbol_json']; echo $symbol_json; ?> <!--This is OK!--></div></center><center><!-- Widget BEGIN --><div class="widget-container"> <div class="widget-container__widget"></div> <div class="widget-copyright"><a href="https://aaaaaaa.com/symbols/<?php echo $row['symbol_html']; ?>/" rel="noopener" target="_blank"><span class="blue-text"><?php echo $row['symbol']?> Symbol Info</span></a></div> <script> var myVar = '<?php echo $symbol_json ?>'; alert(myVar); //This works ok! var myObject = JSON.parse('<?php echo json_encode($symbol_json) ?>'); alert(myObject); //Alert works ok! </script> <script type="text/javascript" src="https://aaaaaaa.com/external-embedding/symbol-info.js" async> { //"symbol": "SDT", //This how it is at present and it works. I need to change it to a variable like below. "symbol": myObject, //Whether I use myObject or myVar (which both contain SDT) the widget loads a different symbol. "width": 1000, "locale": "uk", "colorTheme": "light", "isTransparent": false} </script></div><!-- Widget END -->
1 回答
慕丝7291255
TA贡献1859条经验 获得超6个赞
你为什么不把你的变量放在同一个脚本标签中?作为一般性建议,请不要将 PHP 与 Javascript 或 HTML 混淆。这是让你的代码有味道的最好方法。您必须解析 JSON 才能将其用作变量,因此
var myObject = '<?php echo json_encode($symbol_json) ?>';
成为
var myObject = JSON.parse('<?php echo json_encode($symbol_json) ?>');
- 1 回答
- 0 关注
- 111 浏览
添加回答
举报
0/150
提交
取消