JS在服务器上但未在localhost上发生语法错误

时间:2018-05-01 11:30:53

标签: 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.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"}]');

是什么导致这种情况在一个环境中而不在另一个环境中起作用?我该如何解决这个问题?我在这里看不到任何语法错误?

1 个答案:

答案 0 :(得分:2)

语法错误是由于您的字符串文字本身使用了撇号分隔符\'。你需要逃避你的JSON。这个JSON字符串在哪里生成?

正式发生了什么:

'Canada's more characters... ')

StringLiteral '加拿大' + [lookahead〜= {}]

所以,你显然不应该只是将原始JSON传递给JavaScript源代码。从PHP服务器中撤消引号和撇号。

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

preg_replace('("|\')', '\\$0', $json)