如何在JavaScript中转义来自PHP的文本?

时间:2012-04-04 20:52:02

标签: javascript jquery escaping string-literals html-escape-characters

我正在使用jPlayer显示一些视频,我在php foreach语句中动态创建播放列表:

var playlistacting = 
            [
        <?php foreach($this->result as $val){?>
                {
                    title:  '<?php echo $val->getTitle();?>',
                    artist: '<?php echo $val->getDes();?>',
                    poster: "<?php echo $val->getVideoId();?>.jpg",
                    thumb:  "<?php echo $val->getVideoId();?>.jpg",
                    flv:    "<?php echo $val->getVideoId();?>.flv",
                },
        <?php }?>
];

$val->getDes()示例为I have a one-hour (approximately) solo musical revue called "Manhattan With A Twist". The entire...

我得到的错误是

unterminated string literal
[Break On This Error]   

artist: 'I have a one-hour (approximately)solo musical revue called "Manhattan W...

jquery.js (line 2, col 32)

并且正在向字符串开头的'发展。

我可以这样做:title: "<?php echo htmlspecialchars($val->getTitle());?>",

我会得到同样的错误,但"代替'

我不确定这里发生了什么。是抱怨'未被转义或是什么?

有什么想法吗?

1 个答案:

答案 0 :(得分:4)

只需使用json_encode:

var playlistacting = <?php echo json_encode($this->result);?>;