how to pass an array of objects to jade template?

主宰稳场 提交于 2019-12-04 09:36:13
Max

If I understand correctly, you want to serialize the array of objects into the value of the input. Try this:

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

The first line should turn the array of objects into a string which can then be placed into the value of the input.

Then, when you read the value, you will have to parse the JSON.

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

I'm assuming that your use of $ implies that you are using jQuery.

UPDATE: Explanation

If you want an Object that is in memory in your server to be available to the Javascript running in the browser, you have to "write" that Object onto the page. That process is officially called serialization and the way to do that with Javascript is JSON.stringify. Once on the page in the value of the input, it is just a String. Javascript on the page has to turn that String into an Object (or in this case, an Array of Objects). That's where JSON.parse comes in. Because older browsers don't have JSON.parse, you should use a polyfill like jQuery.parseJSON to ensure that even older browsers will be able to turn the String into a Javascript Object.

By the way, if you don't need the data specifically in the hidden input but you think that that is the best way to do it, let me suggest another way. If your goal is to have var fotos contain the value of datos from the server, you can do that directly in a <script> tag on the page. Here's how to do it in Jade:

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

Check out this question about passing Objects to the page.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!