[英]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. 我试图在我的PHP控制器中生成一个数组,以将数据传递到.twig文件中的javascript。
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: 我可以在.twig中的for循环中访问所有值,但是当尝试在javascript中获取值时,我只能通过以下方式获取整个数组:
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: 当尝试使用javascript中的for循环访问特定值时:
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]. 使用console.log / alert,如果我循环遍历标记[i],则会得到[未定义]标记[i] [0]和[对象对象]。 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. 这是我使用.twig的第一个项目,所以我不知道我是否只是缺少一些明显的东西,因为我似乎找不到我的问题。
Any help would be appreciated! 任何帮助,将不胜感激!
It appears that your issue lies in the javascript for loop. 看来您的问题出在javascript for循环中。
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
. 数组中的所有对象都没有名为
0
的属性。 You only have properties called id
, name
and location
. 您只有名为
id
, name
和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. 您应该看到它显示了每个对象
name
属性的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.