简体   繁体   中英

json_encode won't escape newlines

Firstly, I have search Stack Overflow for the answer, but I have not found a solution that works.

I am using an MVC framework (yii) to generate some views and throw them in an array. Each view is a card, and I have an array of cards ($deck) as well as an array of arrays of cards ($hands, the list of hands for each player). I'm simply trying to set a javascript variable on the front-end to store the hands created in PHP. My view has, it is worth noting, multiple lines. In fact, my current test view consists only of:

test
test

I therefore used json_encode, but it's giving me the following error when I use $.parseJSON():

Uncaught SyntaxError: Unexpected token t

I read elsewhere that it is required (for whatever reason) to use json_encode twice. I have tried this, but it does not help.

With a single json_encode, the output of echoing $hands (followed by an exit) looks pretty healthy:

[["test\ntest","test\ntest","test\ntest","test\ntest", etc...

But when I do not exit, I get a syntax error every time.

Edit: Here is a sample of my code. Note that $cards is an array of HTML normally, but in my simplified case which still errors, includes only the two lines of 'test' as mentioned above.

    $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;

With JavaScript, I am doing the following:

var hands = $.parseJSON('<?php echo json_encode($hands); ?>');

It errors on page load.

Any help would be appreciated!

Thanks,

ParagonRG

var hands = $.parseJSON('<?php echo json_encode($hands); ?>');

This will result in something like:

var hands = $.parseJSON('{"foobar":"baz'"}');

If there are ' characters in the encoded string, it'll break the Javascript syntax. Since you're directly outputting the JSON into Javacript, just do:

var hands = <?php echo json_encode($hands); ?>;

JSON is syntactically valid Javascript. You only need to parse it or eval it if you receive it as a string through AJAX for instance. If you're directly generating Javascript source code, just embed it directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM