Two ways to pass a multiple-line string in PHP to JavaScript _php tips

Source: Internet
Author: User
Tags explode

PHP and JavaScript are beginners. There is a need recently:

For example, there is a multiple-line PHP string:

$a = <<<eof 
thy38 
csdn 
blog 
EOF;

When passed to JavaScript, it is equivalent to:

var c= ' thy38\n\ 
csdn\n\ 
blog ';

Because the understanding of these two languages is so low that you don't know how to Google, you have to find out the two ways:

1. First escape the PHP, then split, then turn to JSON, and then JavaScript parse, and finally use \ n stitching.

var b=json.parse (<?php echo ' \ '. Json_encode (Explode ("\ r \ n", $a)). ' \?>). Join (' \ n '); 

2. Arrange a hidden input on the page, and then give the value to it by PHP, and then the JavaScript reads from it, it realizes the transmission of the multiline value.

<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); 

PS: The above method is in the discussion with a PHP plus JavaScript programmer classmate.
After writing the article back to think about, in fact, these two very winding method is derived from the PHP and JavaScript more than a line of string understanding.
Understanding is also simple, far less complex, direct string replacement on the line:

var d=<?php echo ' \ '. Str_replace ("\ r \ n", "\\n\\\n", $a). ' \ ';?>; 
alert (D==C);

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.