在服务器上而不是本地主机上时出现 JS 未捕获语法错误

JS uncaught syntax error when on server but not localhost

我有一个 php 变量,我正在将其更改为 JS 数组

orderform.blade:

    <?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>

然后在我的 JS 文件中使用变量

var output = entries.reduce(function (orderA, orderB){...

这在本地主机上完美运行。但是当我安装数字海洋云服务器时,我得到:

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 'Canada' + [ 前瞻 ~= { ) } ]

所以,您显然不应该只将原始 JSON 传递给 JavaScript 来源。从您的 PHP 服务器转义引号和撇号。

(我认为 preg_replace 不会替换所有出现的引号,但在 JS 中我知道 json.replace(/'"\''/g, s =>\${s}) 会。)

preg_replace('("|\')', '\[=11=]', $json)