简体   繁体   中英

Passing PHP array into a Javascript array without AJAX or JQuery?

I have a bunch of parallel arrays in php

$phoneNums = array();
$minutesUsed = array();
$plans = array();
$charges = array();

and I'm trying to put them in arrays in JS so I can access them and print values into the page

var phoneNums = <?php echo $phoneNums ?>;
var minutesUsed = <?php echo $minutesUsed ?>;
var plans = <?php echo $plans ?>;
var charge = <?php echo $charges ?>;

What ends up happening is my values end up as undefined. How would I pass an array from php to js this without using AJAX or JQuery?

Echoing a PHP array will not print its contents. Even if it would, it would not be in the same format that Javascript expects ( [1,2,3] ) - also, associative arrays in PHP work quite differently than JS, where they are objects ( {'x':1,'y':2} ).

JSON is Javascript Object Notation. If you encode your data in JSON (in PHP, you can use json_encode() to do that), it will be absolutely acceptable for Javascript, so you can simply print it:

var phoneNums = <?php echo json_encode($phoneNums); ?>;

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM