Home > Backend Development > PHP Tutorial > Two ways to pass multi-line strings in PHP to JavaScript_PHP Tutorial

Two ways to pass multi-line strings in PHP to JavaScript_PHP Tutorial

WBOY
Release: 2016-07-13 10:24:36
Original
824 people have browsed it

PHP和JavaScript都是初学。最近有这么个需求:

比方说有一个PHP的多行字符串:

$a = <<<EOF 
thy38 
csdn 
blog 
EOF;
Copy after login

传递给JavaScript后要等价于:

var c='thy38\n\ 
csdn\n\ 
blog';
Copy after login

因为对这两门语言的理解低到不知如何Google,只好自己摸索出方法两则:

1. 将PHP先转义,然后分割,然后转JSON,然后JavaScript parse,最后用\n拼接。

var b=JSON.parse(<&#63;php echo '\''.json_encode(explode("\r\n", $a)).'\''; &#63;>).join('\n'); 
alert(b==c); 
Copy after login

2. 在页面上安排一个隐藏的input,然后先由php把值给它,然后JavaScript从它里面读,就实现了多行值的传递

<input type="hidden" id='testphp' value="<&#63;php echo $a&#63;>" /> 
var a=document.getElementById("testphp").value; 
var b=JSON.parse(<&#63;php echo '\''.json_encode(explode("\r\n", $a)).'\''; &#63;>).join('\n'); 
alert(a==b); 
alert(b==c); 
Copy after login

PS: 以上方法是在跟一个PHP加JavaScript程序员同学的讨论中逐步得出的。
写完了文章回头再想想,其实这两个很绕的方法还是源于对PHP和JavaScript的多行字符串理解不透。
理解透了也就简单了,远不用这么复杂,直接字符串替换就行:

var d=<&#63;php echo '\''.str_replace("\r\n", "\\n\\\n", $a).'\''; &#63;>; 
alert(d==c);
Copy after login

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/825410.htmlTechArticlePHP和JavaScript都是初学。最近有这么个需求: 比方说有一个PHP的多行字符串: $a = EOF thy38 csdn blog EOF; 传递给JavaScript后要等价于: var c='thy...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template