我想将一个对象数组从 mongodb 传递给客户端...
这是对象
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:"#",
},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 的对象数组
我试图在 jade 中放入一个变量
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)
}
控制台日志打印undefined
这是为什么呢???我怎样才能在客户端正确地从数据库中获取信息??? 全部发送
最佳答案
如果我没理解错的话,你想将对象数组序列化为 value
的输入。试试这个:
- var jsonString = JSON.stringify(datos)
input(type='hidden',id='imagenes',value=jsonString)
第一行应该将对象数组转换为一个字符串,然后可以将该字符串放入输入值中。
然后,当您读取该值时,您将不得不解析 JSON。
var fotos = $.parseJSON($('#imagenes1').val());
我假设您使用 $
暗示您正在使用 jQuery。
更新:解释
如果您希望服务器内存中的对象可用于浏览器中运行的 Javascript,您必须将该对象“写入”到页面上。该过程正式称为序列化,使用 Javascript 执行此操作的方法是 JSON.stringify
.一旦进入 value
中的页面输入的,它只是一个字符串。页面上的 Javascript 必须将该字符串转换为对象(或在本例中为对象数组)。这就是 JSON.parse 的用武之地。因为旧版浏览器没有 JSON.parse,所以您应该使用 jQuery.parseJSON 之类的 polyfill 来确保即使是旧版浏览器也能够将字符串转换为 Javascript 对象。
顺便说一句,如果您不需要 hidden
中的数据input
但是您认为这是最好的方法,让我建议另一种方法。如果你的目标是拥有 var fotos
包含 datos
的值从服务器,您可以直接在 <script>
中执行此操作页面上的标记。以下是在 Jade 中的实现方法:
script
var fotos = #{JSON.stringify(datos)};
查看 this question关于将对象传递给页面。
关于javascript - 如何将一组对象传递给 Jade 模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12960575/