json_encode不会逃脱换行符

Par*_*gon 0 javascript php json yii

首先,我有搜索Stack Overflow的答案,但我还没有找到一个有效的解决方案.

我正在使用MVC框架(yii)生成一些视图并将它们放入数组中.每张视图都是一张牌,我有一系列牌($ deck)以及一系列牌($ hands,每个牌手的牌局).我只是想在前端设置一个javascript变量来存储用PHP创建的指针.值得注意的是,我的观点有多条线.实际上,我当前的测试视图仅包含:

test
test
Run Code Online (Sandbox Code Playgroud)

因此我使用了json_encode,但是当我使用$ .parseJSON()时它会给我以下错误:

Uncaught SyntaxError: Unexpected token t
Run Code Online (Sandbox Code Playgroud)

我在别处读到,需要(无论出于何种原因)两次使用json_encode.我试过这个,但没有用.

使用单个json_encode,echoing $hands(后跟退出)的输出看起来非常健康:

[["test\ntest","test\ntest","test\ntest","test\ntest", etc...
Run Code Online (Sandbox Code Playgroud)

但是当我不退出时,每次都会出现语法错误.

编辑:这是我的代码示例.请注意,$ cards通常是一个HTML数组,但在我的简化情况下仍然存在错误,仅包括上面提到的两行'test'.

    $deck = array();
    foreach ($cards as $card) {
        $deck[] = $this->renderPartial('/gamePieces/cardTest', 
                array('card'=>$card), true);
    }
    $hands = Cards::handOutCards($deck, $numCards , $numPlayers);
    $hands = json_encode($hands);

    echo $hands; exit;
Run Code Online (Sandbox Code Playgroud)

使用JavaScript,我正在执行以下操作:

var hands = $.parseJSON('<?php echo json_encode($hands); ?>');
Run Code Online (Sandbox Code Playgroud)

它在页面加载时出错.

任何帮助,将不胜感激!

谢谢,

ParagonRG

dec*_*eze 5

var hands = $.parseJSON('<?php echo json_encode($hands); ?>');
Run Code Online (Sandbox Code Playgroud)

这将导致类似于:

var hands = $.parseJSON('{"foobar":"baz'"}');
Run Code Online (Sandbox Code Playgroud)

如果'编码字符串中有字符,它将破坏Javascript语法.由于您直接将JSON输出到Javacript,只需执行以下操作:

var hands = <?php echo json_encode($hands); ?>;
Run Code Online (Sandbox Code Playgroud)

JSON是语法上有效的Javascript.eval如果您通过AJAX将其作为字符串接收,则只需要解析它.如果您直接生成Javascript源代码,只需直接嵌入即可.