简体   繁体   English

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

[英]How to escape text coming from PHP in JavaScript?

I am using jPlayer to display some videos and I create the playlist on the fly in a php foreach statement:我正在使用 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 }?>
];

and $val->getDes() example would be I have a one-hour (approximately) solo musical revue called "Manhattan With A Twist". The entire...$val->getDes()的例子是I have a one-hour (approximately) solo musical revue called "Manhattan With A Twist". The entire... I have a one-hour (approximately) solo musical revue called "Manhattan With A Twist". The entire...

the error I get is我得到的错误是

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)

and is poining to the ' at the beginning of the string.并指向字符串开头的'

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

and I will get the same error but with " instead of ' .我会得到同样的错误,但用"而不是'

I'm not sure what is happening here.我不确定这里发生了什么。 Is it complaining about that ' not being escaped or what?是在抱怨'没有被转义还是什么?

Any ideas?有任何想法吗?

simply use json_encode:只需使用 json_encode:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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