I have a array of objects like this in php:
Array
(
[0] => Array
(
[id] => 1
[text] => aa
)
[1] => Array
(
[id] => 2
[text] => valladolid
)
[2] => Array
(
[id] => 3
[text] => valencia
)
)
I use json_encode to convert array in php to javascript
var data = '{{listCountries|json_encode|raw}}';
And this, they transform in:
var data = '[{"id":1,"text":"aa"},{"id":2,"text":"valladolid"},{"id":3,"text":"valencia"}]';
And i need, without single-quotes:
var data = [{"id":1,"text":"aa"},{"id":2,"text":"valladolid"},{"id":3,"text":"valencia"}];
JavaScript will receive your perfectly encoded JSON in String format, You have to DECODE/PARSE it
JSON.parse(YOUR_STRING); // native JavaScript JSON parser, supported in major wab browsers
jQuery.parseJSON(); // for JQuery
...
var data = JSON.parse('{{listCountries|json_encode|raw}}')
EDIT: paste that into your php template and you should be good to go! Credit goes to @Andreas for finding it first.
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.