在AJAX调用(使用ExpressJS)后,在EJS模板中循环遍历数组的正确方法是什么?

时间:2016-07-04 07:29:08

标签: ajax node.js express ejs requestjs

因此,我尝试使用request模块/包将我从http调用使用的对象数组循环到我的内部API。到目前为止,我能够从API获取数据并在我的页面上显示完整对象。我想在我的页面上显示它并使用EJS模板系统循环它。我知道我可以使用AngularJS作为前端的东西,但我想看看我能在多大程度上只用服务器端。

以下是我的代码:

server.js

// Prepend /api to my apiRoutes
app.use('/api', require('./app/api'));

api.js

var Report = require('./models/report');
var express  = require('express');
var apiRoutes = express.Router();

apiRoutes.route('/reports', isLoggedIn)  
     .get(function (req, res,next) {
          // use mongoose to get all reports in the database
          Report.find(function (err, reports) {
                 // if there is an error retrieving, send the error.
                 // nothing after res.send(err) will execute
                 if (err)
                    return res.send(err);
                    res.json(reports);
          });
    });

routes.js

var User = require('./models/user');
var request = require('request');
module.exports = function (app, passport) {

    app.get('/reports', isLoggedIn, function (req, res) {
        res.render('pages/new-report.ejs', {
            user: req.user,
            title:'New Report'
        });
    });


    request({
        uri:'http://localhost:2016/api/reports',
        method:'GET'
    }).on('data',function(data){
        console.log('decoded chunk:' + data)
    }).on('response',function(resp){
        resp.on('data', function(data){
            console.log('received:' + data.length + ' bytes of compressed data');
            app.get('/timeline', isLoggedIn, function (req, res) {
                res.render('pages/timeline', {
                    user: req.user,
                    title:'Timeline',
                    reports: data
                });
            });
        })
    }); 
}  

reports.ejs
因此,如果我只是在我的页面上输出整个reports对象,就像这个<p><%= reports %></p>一样,一切正常,我会得到这样的结果:

[
  {
    "_id": "5775d396077082280df0fbb1",
    "author": "57582911a2761f9c77f15528",
    "dateTime": "30 June 2016 - 07:18 PM",
    "picture": "",
    "description": "",
    "location": [
      -122.46596999999997,
      37.784495
    ],
    "latitude": 37.784495,
    "longitude": -122.46596999999997,
    "address": "4529 California St, San Francisco, CA 94118, USA",
    "contact": "John Doe",
    "type": "Financial",
    "__v": 0,
    "updated_at": "2016-07-01T02:21:10.259Z",
    "created_at": "2016-07-01T02:21:10.237Z",
    "tags": [
      "tag1,tag2"
    ]
  }
]

但是,如果我尝试循环遍历对象,如下所示它得到 UNDEFINED 作为我的报告对象的返回属性,我显然得到了一个无限循环。

<ul class="timeline">
    <% reports.forEach(function(report) { %>
    <li class="timeline-yellow">
        <div class="timeline-time">
            <span class="date" style="text-align:left">
            <%= report.type %> </span>
            <span class="time" style="font-weight:700;font-size:25px;line-height:20px;text-align:left;">
            <%= report.dateTime %> </span>
        </div>
    </li>
    <% }) %>
</ul>

我尝试过循环的另一种变体,但我仍然没有成功:

<ul class="timeline">
    <% for (var i = 0; i < reports.length; i++) { %>
    <li class="timeline-yellow">
        <div class="timeline-time">
            <span class="date" style="text-align:left">
            <%= report[i].type %>
            4/10/13 </span>
            <span class="time" style="font-weight:700;font-size:25px;line-height:20px;text-align:left;">
            <%= report[i].dateTime %> </span>
        </div>
    </li>
    <% } %>
</ul>

4 个答案:

答案 0 :(得分:10)

forejs循环的语法是完美的,但迭代的数组名称是报告,您似乎使用 report [i] 迭代内部,需要更改为 reports [i] ,这应该有效。

reports.ejs

<ul class="timeline">
    <% for (var i = 0; i < reports.length; i++) { %>
    <li class="timeline-yellow">
        <div class="timeline-time">
            <span class="date" style="text-align:left">
            <%= reports[i].type %>
            4/10/13 </span>
            <span class="time" style="font-weight:700;font-size:25px;line-height:20px;text-align:left;">
            <%= reports[i].dateTime %> </span>
        </div>
    </li>
    <% } %>
</ul>

希望这有帮助。

答案 1 :(得分:0)

I guess something like this .. 

<% if (reports.length > 0){%> // Checking if there are reports
  <ul class="timeline">
      <%  for (let report of reports){ %>
        <li class="timeline-yellow">
          <div class="timeline-time">
            <span class="date" style="text-align:left">
              <%= report.type %> 
               4/10/13 </span>
              <span class="time" style="font-weight:700;font-size:25px;line- 
  height:20px;text-align:left;">
              <%= report.dateTime %> </span>
          </div>
      </li>
      <% } %>
  </ul>
 <%}%>
<%}%>

答案 2 :(得分:0)

这是我使用 loopback3 和 ejs 的工作版本:

在 server/boot/routes.js 中:

module.exports = function(app) {
  const router = app.loopback.Router();

  router.get('/', function(req, res){
    app.models.ZenGarden.find()
        .then(plants => {
          console.log('plants: ', plants)
          res.render('index', {plants:plants})
        }).catch(err => {
          console.log('Failed to find in ZenGarden: ', err)
          res.render('index')
        })
  });

  router.post('/', function(req, res){
    var plants = req.body.plants;
    if (plants) {
      for (var i = 0; i < plants.length; i++) {
        console.log(plants[i])
        app.models.ZenGarden.upsert(plants[i])
            .then().catch(err => console.log(err))
      }
    }
    return res.render('index', {plants:plants})
  })

  app.use(router);
};

在 server/views/index.ejs 中:

<div>
    <form action='/' method='POST'>
        <% if (plants) { %>
            <table>
                <tr><td>Name</td><td>Count</td></tr>
                <% for (var i = 0; i < plants.length; i++) { %>
                    <tr>
                        <input type='hidden' value=<%= plants[i].id %> name='plants[<%= i %>][id]'>
                        <input type='hidden' value="<%= plants[i].name %>" name='plants[<%= i %>][name]'>
                        <td><%= plants[i].name %></td>
                        <td><input type='text' value=<%= plants[i].count %> name='plants[<%= i%>][count]'</td></tr>
                <% } %>
            </table>
            <button type='submit'>Save</button>
        <% } else { %>
            <p>No plant in Zen Garden :-(</p>
        <% } %>
    </form>
</div>

确保在 server/server.js 中添加以下内容:

const path = require('path')
const bodyparser = require('body-parser')

app.set('view engine', 'ejs')
app.set('views', path.resolve(__dirname, 'views'))

app.middleware('initial', bodyparser.urlencoded({extended:true}))
app.middleware('initial', bodyparser.json())

这里是模型 ZenGarden(common/models/zen-garden.json) 的定义:

{
  "name": "ZenGarden",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "name": {
      "type": "string",
      "required": true
    },
    "count": {
      "type": "number",
      "required": true
    }
  },
  "validations": [],
  "relations": {},
  "acls": [],
  "methods": {}
}

答案 3 :(得分:-1)

Async是一个实用程序模块,它提供了使用异步JavaScript的直接,强大的功能。虽然最初设计用于Node.js并可通过

安装

npm install --save async

有关文档,请访问http://caolan.github.io/async/

<强>实施例

// assuming openFiles is an array of file names and saveFile is a function
// to save the modified contents of that file:

async.each(openFiles, saveFile, function(err){
    // if any of the saves produced an error, err would equal that error
});
// assuming openFiles is an array of file names

async.each(openFiles, function(file, callback) {

  // Perform operation on file here.
  console.log('Processing file ' + file);

  if( file.length > 32 ) {
    console.log('This file name is too long');
    callback('File name too long');
  } else {
    // Do work to process file here
    console.log('File processed');
    callback();
  }
}, function(err){
    // if any of the file processing produced an error, err would equal that error
    if( err ) {
      // One of the iterations produced an error.
      // All processing will now stop.
      console.log('A file failed to process');
    } else {
      console.log('All files have been processed successfully');
    }
});