简体   繁体   中英

Pulling data from an array made in php and passing it to javascript twig

I am trying to get an array produced in my php controller to pass data to javascript in a .twig file.

I am able to access all the values in a for loop in the .twig but when trying to get the value in javascript, I am only able to get the whole array by using:

var markers = {{ products|json_encode|raw }};

This produces:

var markers = [{"id":"1","name":"x","location":"San Diego"},{"id":"2","name":"y","location":"LA"}];

When trying to access specific values using a for loop within the javascript:

for (i = 0; i < markers.length; i++) 
{ 
alert(markers[i][0])
} 

Using console.log / alert I get [undefined] for markers[i][0] and [object object] if I loop through markers[i]. The length is correct.

This is my first project using .twig so I don't know if I am just missing something really obvious as I can't seem to find my problem.

Any help would be appreciated!

It appears that your issue lies in the javascript for loop.

Look here:

var markers = [{"id":"1","name":"x","location":"San Diego"},{"id":"2","name":"y","location":"LA"}];

None of the objects within your array have a property named 0 . You only have properties called id , name and location .

Change your loop to something like:

for (i = 0; i < markers.length; i++) 
{ 
  alert(markers[i]['name'])
} 

You should see it shows you the value of each objects name property.

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