Two methods for passing multi-line strings to JavaScript in PHP

Source: Internet
Author: User
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);

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.