将多行php字符串传递给javascript函数/变量 [英] passing php string with multiple lines to a javascript function/variable
问题描述
我正在其他人的网站上工作,它的逻辑非常愚蠢! 无论如何,有一个php变量,其中包含一个来自数据库的字符串.
I'm working on someone else's website and it has a very stupid logic! Anyway, there is a php variable which contains a string which comes from database.
$x = ' aaaa
bbb
ccc
gggg ';
,我需要将此字符串提供给javascript函数:
and I need to feed this string to a javascript function:
<script>
var x = "<?php echo $x ; ?>";
some_function(x);
</script>
如您所知,我最终会遇到一个错误,因为javascript变量如果不将多个行合并在一起就不能包含多行:
As you know I end up with an error because a javascript variable cannot contain multiple lines without joining them together like this:
var x = ' i '+
' have '+
' different lines';
我该怎么做?它是否删除行或正确设置格式都没关系,我只是想摆脱此错误.
How can I do this? It doesn't matter if it removes the lines or formats it properly, I just want to get rid of this error.
推荐答案
将字符串传递到 json_encode 使其正确逃脱.如果要输出到HTML文档,请确保将JSON_HEX_TAG
作为选项的一部分传递,以转义<
和>
并防止恶意用户尽早结束</script>
标签并引入XSS漏洞
Pass the string into json_encode to properly escape it. If you're outputting to an HTML document, make sure to pass JSON_HEX_TAG
as part of the options, to escape <
and >
and prevent a malicious user from ending your </script>
tags early and introducing an XSS exploit.
这篇关于将多行php字符串传递给javascript函数/变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!