[英]json_encode won't escape newlines
Firstly, I have search Stack Overflow for the answer, but I have not found a solution that works. 首先,我已经在Stack Overflow上搜索了答案,但是没有找到有效的解决方案。
I am using an MVC framework (yii) to generate some views and throw them in an array. 我正在使用MVC框架(yii)生成一些视图并将它们放入数组中。 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).
每个视图都是一张纸牌,我有一张纸牌数组($ deck)以及一张纸牌数组的数组($ hands,每个玩家的手牌列表)。 I'm simply trying to set a javascript variable on the front-end to store the hands created in PHP.
我只是想在前端设置一个javascript变量来存储用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(): 因此,我使用了json_encode,但是当我使用$ .parseJSON()时却出现了以下错误:
Uncaught SyntaxError: Unexpected token t
I read elsewhere that it is required (for whatever reason) to use json_encode twice. 我在其他地方读到了(无论出于何种原因)需要两次使用json_encode。 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: 使用单个json_encode,回显
$hands
的输出(紧随出口)看起来非常健康:
[["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.
请注意,$ 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;
With JavaScript, I am doing the following: 使用JavaScript,我可以执行以下操作:
var hands = $.parseJSON('<?php echo json_encode($hands); ?>');
It errors on page load. 页面加载错误。
Any help would be appreciated! 任何帮助,将不胜感激!
Thanks, 谢谢,
ParagonRG 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. 如果编码后的字符串中包含
'
字符,则会破坏Javascript语法。 Since you're directly outputting the JSON into Javacript, just do: 由于您将JSON直接输出到Javacript中,因此请执行以下操作:
var hands = <?php echo json_encode($hands); ?>;
JSON is syntactically valid Javascript. JSON是语法上有效的Javascript。 You only need to parse it or
eval
it if you receive it as a string through AJAX for instance. 例如,如果您通过AJAX将其作为字符串接收,则只需要解析或
eval
它即可。 If you're directly generating Javascript source code, just embed it directly. 如果您直接生成Javascript源代码,则直接将其嵌入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.