2012-10-18 53 views
4

我想通过从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的

和IM试图把一个变量里面玉

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) 
      } 

控制台日志打印未定义

这是为什么?我怎样才能从客户端正确地得到数据库的信息? tnx全部

+2

你的问题还不够清楚。你想达到什么目的? – Max

+0

我想把对象数组隐藏在输入中隐藏“imagenes” – andrescabana86

回答

8

如果我理解正确,您想将对象数组序列化为输入的value。尝试:

- var jsonString = JSON.stringify(datos) 
input(type='hidden',id='imagenes',value=jsonString) 

第一行应打开对象的数组然后可以被放置到输入的值的字符串。

然后,当您读取值时,您将不得不解析JSON。

var fotos = $.parseJSON($('#imagenes1').val()); 

我假设你的$使用意味着你正在使用jQuery。

UPDATE:说明

如果你想要一个Object,它是在内存中的服务器可用给Javascript在浏览器中运行的,你要“写”该对象到页面上。该过程被正式称为序列化,并且使用Javascript的方法是JSON.stringify。一旦在输入的value的页面上,它只是一个字符串。页面上的Javascript必须将该String转换为Object(或者在这种情况下为对象Array)。这就是JSON.parse的用武之地。因为旧版浏览器没有JSON.parse,所以应该使用像jQuery.parseJSON这样的polyfill来确保旧版浏览器能够将字符串转换为Javascript对象。顺便说一下,如果您不需要hiddeninput中的数据,但您认为这是最好的方式,那么让我以另一种方式提出建议。如果您的目标是让var fotos包含来自服务器的值datos,则可以直接在页面上的<script>标记中执行此操作。以下是如何做到这一点在玉:

script 
    var fotos = #{JSON.stringify(datos)}; 

退房this question约传递对象到页面上。

+0

嗯所以我必须再次stringify数组和parseJSON获取对象...谢谢你这个工作对我来说!但如果你可以解释为什么我apreciate,因为我不明白为什么我必须stringify和恢复过程与parseJSON ... – andrescabana86

+1

我更新了解释的答案。 – Max