Two Ways of Passing Multiline Strings from PHP to JavaScript
- 2021-07-01 06:53:08
- OfStack
PHP and JavaScript are both beginners. Recently, there is such a demand:
For example, there is a multi-line string with one PHP:
$a = <<<EOF
thy38
csdn
blog
EOF;
Passed to JavaScript is equivalent to:
var c='thy38\n\
csdn\n\
blog';
Because the understanding of these two languages is so low that I don't know how to Google, I have to find two ways:
1. Escape PHP first, then split it, then turn it to JSON, then JavaScript parse, and finally splice it with\ n.
var b=JSON.parse(<?php echo '\''.json_encode(explode("\r\n", $a)).'\''; ?>).join('\n');
alert(b==c);
2. Arrange a hidden input on the page, then give it the value by php first, and then read it by JavaScript, thus realizing multi-line value transfer
<input type="hidden" id='testphp' value="<?php echo $a?>" />
var a=document.getElementById("testphp").value;
var b=JSON.parse(<?php echo '\''.json_encode(explode("\r\n", $a)).'\''; ?>).join('\n');
alert(a==b);
alert(b==c);
PS: The above method was gradually obtained in the discussion with a classmate of PHP plus JavaScript programmers.
After writing the article, think back. In fact, these two methods are still due to the incomprehension of PHP and JavaScript multi-line strings.
It is simple to understand thoroughly, far from being so complicated, just replace the string directly:
var d=<?php echo '\''.str_replace("\r\n", "\\n\\\n", $a).'\''; ?>;
alert(d==c);