如何将对象传递给客户端Javascript - NodeJS&表现 [英] How to Pass an Object to client Javascript - NodeJS & express

查看:119
本文介绍了如何将对象传递给客户端Javascript - NodeJS&表现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一些问题,我试图在我的Javascript客户端发送一个对象,只要我呈现视图。我以这种方式发送(使用Handlebars的Im)

 > locations = [{
> local:my_local,
> desc:myDesc
> }];

res.render('myView',{locaciones:locaciones});

//然后在我的视图中在脚本标记内我尝试获取该var并打印它

 < script> 
var myObj ='{{locations}}';
console.log(locations);
< / script>

结果如下:

  [object] 

我无法使用它的任何属性因为它是未定义的

解决方案

您可以将您的对象作为字符串发送。

locations = JSON.stringify({local:my_local,desc:myDesc});



在客户端,你可以解析它得到一个对象



loc = JSON.parse(locations);



现在你可以使用loc作为Object。


I'm having a little bit problems, I'm trying to send an object to use on my Javascript client side, whenever I render the view. I am sending it this way (Im using Handlebars)

  > locations=[ {
    >               local:"my_local",                    
    >                desc:"myDesc"                  
    >               }]; 

res.render('myView', { locaciones:locaciones });

// Then in my view Inside a script tag i try to get that var and print it

<script>
  var myObj='{{locations}}';
   console.log(locations);
</script>

the result is this :

[object]

and I can't use any property of it because it's undefined

解决方案

You can send your object as a string.

Like locations = JSON.stringify({local:"my_local",desc:"myDesc"});

And on client side you can parse it to get an Object

Like loc = JSON.parse(locations);

Now you can use loc as Object.

这篇关于如何将对象传递给客户端Javascript - NodeJS&amp;表现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆