PHP Tip: Use Json_encode () to assign a value to a JS array

Source: Internet
Author: User
This article detailed the Json_encode () to the JS array assignment related content.

1. Use Json_encode () to assign a value to the JS array

Most of the time, we have to pay the PHP processing results to JS to deal with. However, when assigning a value to JS, the assignment of a single variable is simple and easy to implement, as long as the template tag directly output PHP variables. For example:

PHP: $this->title= ' I love thinkphp '; Js:<script>var title= "{$title}";</script>


In this way, the $title value of the PHP variable can be processed in JS ~

However, when we assign the array of PHP processing to an array of JS, we encounter a lot of problems. If you assign a value directly like a single variable, JS cannot read the elements in the array.

In the actual application, I used the json_encode () This function to work with the PHP array, so that the PHP processing can be easily processed in the array, in JSON data format to the JS, as well, JS is also a JSON data format array. For example:

PHP: $this->myarr=array (' Think ', ' php ', ' China '); Js:<script>var Myarray={:json_encode ($myarr)};  Note, do not use double or single quotes here; var arr = <!--? php echo json_encode ($arr, json_pretty_print)?-->;</script>


This time, JS in the myarray=[' Think ', ' PHP ', ' China '; Such a JSON-formatted array, which is handled in JS is fairly easy to handle.

Using the Json_encode () function, you can easily assign a PHP array to the JS array ~

This article explains the Json_encode () to the JS array assignment related content, more relevant content please pay attention to the PHP Chinese network.

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.