如何将一个对象数组传递给玉模板?
我想从mongodb传递一个对象数组到客户端…
这是对象
var objeto_img= { name:'name of the file', image:'image.jpg url', title:'title of the image', caption:'descripcion of the image', link:"#", };
在一些configuration文件中是很多图像,所以这是一个像这样的对象数组
[var objeto_img= { name:'name of the file', image:'image.jpg url', title:'title of the image', caption:'descripcion of the image', link:"#", },var objeto_img= { name:'name of the file', image:'image.jpg url', title:'title of the image', caption:'descripcion of the image', link:"#", },var objeto_img= { name:'name of the file', image:'image.jpg url', title:'title of the image', caption:'descripcion of the image', link:"#", };]
这是服务器代码
res.render('index/perfil_publicacion_contenido', { datos:datosRecibidos })
datosRecibidos是来自mongodb的对象数组
并试图在玉内置variables
input(type='hidden',id='imagenes',value=datos.img)
但是当我尝试获取对象
var fotos=$('#imagenes1').val(); for(foto in fotos) { console.log(fotos[foto].image) console.log(fotos[foto].name) console.log(fotos[foto].caption) console.log(fotos[foto].title) }
控制台日志打印未定义
这是为什么??? 我怎样才能从客户端正确地得到数据库的信息? 全部都是
如果我理解正确,你想序列化对象的数组到input的value
。 尝试这个:
- var jsonString = JSON.stringify(datos) input(type='hidden',id='imagenes',value=jsonString)
第一行应该将对象数组转换为一个string,然后可以将其放入input的值中。
然后,当你读取的值,你将不得不parsingJSON。
var fotos = $.parseJSON($('#imagenes1').val());
我假设你使用$
意味着你正在使用jQuery。
更新:解释
如果您希望服务器中内存中的Object可用于在浏览器中运行的Javascript,则必须将该Object写入该页面。 这个过程被正式称为序列化,用Javascript来做这件事的方式是JSON.stringify
。 一旦在input的value
的页面上,它只是一个string。 页面上的Javascript必须将该string转换为一个对象(或在这种情况下,一个对象数组)。 这就是JSON.parse的用处。因为旧的浏览器没有JSON.parse,所以应该使用像jQuery.parseJSON这样的polyfill,以确保即使是较旧的浏览器也能够将string转换为一个Javascript对象。
顺便说一句,如果你不需要hidden
input
数据,但你认为这是最好的方法,让我以另一种方式build议。 如果您的目标是让var fotos
包含来自服务器的数据值,那么您可以直接在页面上的<script>
标记中进行此操作。 以下是如何在Jade中做到这一点:
script var fotos = #{JSON.stringify(datos)};
看看这个关于传递对象到页面的问题。