Possible Duplicate:
Pass a PHP string to a Javascript variable (including escaping newlines)
I have a PHP array that I want to use in a javascript script. I suppose that I will have to convert it to a string that can be understood by javascript, and embed the string inside the script. What is the best way to accomplish this.
EDIT - This is for initial load of the page, not subsequent AJAX call
$textMessages = array();
-
1See 1st answer on stackoverflow.com/questions/1968977/…KillerX– KillerX2012年02月05日 15:21:50 +00:00Commented Feb 5, 2012 at 15:21
3 Answers 3
You could use JSON.
json_encode and json_decode on the server side and JSON.stringify and JSON.parse on the client side. Both client side functions are natively built-into modern browsers but if you need to support legacy browsers you could include the json2.js script to your page.
Comments
json_encode(). Put in a PHP array, receive a string representation of a JS array.
Comments
JSON is perfect for this.
echo json_encode($textMessages);