This article mainly introduces two methods for passing multi-line strings to JavaScript in PHP. For more information, see PHP and JavaScript. There is a need recently:
For example, there is a PHP multi-line string:
$ A = <
After being passed to JavaScript, it is equivalent:
var c='thy38\n\ csdn\n\ blog';
Because I do not know how to Google these two languages, I have to find two methods:
1. escape PHP first, split it, convert it to JSON, convert it to JavaScript parse, and 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, and then the php will first give the value to it, and then the JavaScript will read from it, and the multi-row value will be passed.
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 is gradually obtained from a discussion with a PHP and JavaScript programmer.
After writing the article, let's look back. In fact, these two methods are still due to a lack of understanding of the multi-line strings of PHP and JavaScript.
It's easy to understand. you can simply replace strings without such complexity:
var d=<?php echo '\''.str_replace("\r\n", "\\n\\\n", $a).'\''; ?>; alert(d==c);