Javascript 在服务器上而不是本地主机上时出现JS uncaught语法错误
我有一个php变量,我正在将其转换为JS数组 orderform.blade:Javascript 在服务器上而不是本地主机上时出现JS uncaught语法错误,javascript,digital-ocean,Javascript,Digital Ocean,我有一个php变量,我正在将其转换为JS数组 orderform.blade: <?php foreach ($entries as $entry){ $name[] = $entry->name; $quantity[] = $entry->quantity; } ?> <script type="text/javascript"> var entries = JSON.pa
<?php
foreach ($entries as $entry){
$name[] = $entry->name;
$quantity[] = $entry->quantity;
}
?>
<script type="text/javascript">
var entries = JSON.parse('<?php echo json_encode($entries) ?>');
// console.log(entries);
</script>
这在本地主机上非常有效。但当我使用数字海洋云服务器时,我得到:
Uncaught SyntaxError: missing ) after argument list
Uncaught ReferenceError: entries is not defined at javascript.js:12
缺少)错误突出显示了以下内容:
var entries = JSON.parse('[{"id":2,"name":"Britannia","mint":"The Royal Mint","quantity":"3","weight":"31.15","price":"19.00","description":"Royal Mint flagship silver bullion. CGT free.","created_at":"2018-05-01 03:08:38","updated_at":"2018-05-01 03:27:23"},{"id":3,"name":"Maple Leaf","mint":"The Royal Canadian Mint","quantity":"12","weight":"31.15","price":"17.50","description":"Canada's flagship bullion coin. Prone to milk spots.","created_at":"2018-05-01 10:41:57","updated_at":"2018-05-01 10:41:57"}]');
是什么原因导致它在一个环境中工作而不在另一个环境中工作?我如何解决这个问题?我在这里看不到任何语法错误?语法错误是由于字符串文字本身使用撇号分隔符\'造成的。您需要转义JSON。这个JSON字符串是在哪里生成的 正式发生的事情:
'Canada's more characters... ')
StringLiteral“加拿大”+[lookahead~={)]
所以,您显然不应该只将原始JSON传递给JavaScript源代码。从PHP服务器中转义引号和撇号
(我认为,preg\u replace
不会替换所有出现的引号,但在JS中我知道json.replace(/''''\''/g,s=>
\${s})
会。)
邪恶的
加拿大的
…:)正确!你对细节有多么好的眼光!语法突出显示是你的朋友:)它正在从我的数据库中提取。不过我希望仍然能够在文本中使用撇号。@Dan是的,但你需要用JavaScript文本来转义它,即“Canada\\\'s”
;只需插入一个反向的条形符号即可我想,你的撇号是有原因的。
'Canada's more characters... ')
preg_replace('("|\')', '\\$0', $json)