将JSON从PHP传递到JAVASCRIPT [复制]

bnl4lu3b  于 2023-05-02  发布在  PHP
关注(0)|答案(1)|浏览(128)

此问题已在此处有答案

Can I interpolate the result of json_encode directly into JavaScript code, or do I have to use JSON.parse?(2个答案)
23小时前关闭

$testArray = array("John", "Mary", "Peter", "Sally");
$myTest = json_encode($testArray);
$javascript = "
                <script>
                const displayExternalUrl = JSON.parse($myTest);
                console.log(displayExternalUrl);
                 </script>
                 ";
echo $javascript;

我尝试将$myTest(PHP)传递给constdisplayExternalUrl(Javascript),日志显示
caught SyntaxError: Unexpected token 'J', "John,Mary,"... is not valid JSON at JSON.parse (<anonymous>)
错误代码在哪里?

dwbf0jvd

dwbf0jvd1#

设置

$javascript = "<script>
const displayExternalUrl = JSON.parse(`$myTest`);
console.log(displayExternalUrl);
</script>";

使用反引号中的$myTest变量
或引用

$javascript = "<script>
            const displayExternalUrl = '$myTest';
            console.log(JSON.parse(displayExternalUrl));
             </script>";

相关问题