在Node.js

时间:2015-07-28 08:47:13

标签: node.js undefined ejs cheerio

我试图在node.js上以ejs作为我的模板运行Cheerio。每当我运行服务器时,我都会得到#undefined'在' console.log'。以下是我的代码。

服务器端 app.js



/**
 * Module dependencies.
 */

var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path')
  , request = require ('request')
  , cheerio = require ('cheerio');
 var $ = cheerio.load('<ul id="fruits">...</ul>');

var app = express();
console.log($('[class = "orange"]').attr('id'));
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

app.get('/', routes.index);
app.get('/users', user.list);


var temp = $('[class="orange"]').attr('id');
app.get('/data', function(req, res){
	console.log(temp);
	  res.send(temp); //replace with your data here
}).listen(3000);
&#13;
&#13;
&#13;

index.ejs

&#13;
&#13;
<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js" type="text/javascript"></script>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>

  <body>
    <h1><%= title %></h1>
      <input type="button" id="stopButton" value="Stop Listening"/>
    <p>Welcome to <%= title %></p>
  <ul id="fruits">
  <li id= "1" class="apple">Apple</li>
  <li id = "2" class="orange">Orange</li>
  <li id = "3" class="pear">Pear</li>
</ul>
  <script type="text/javascript">
      $(document).ready(function () {
          $('#stopButton').click(function () {
              $.get('http://localhost:3000/data', {}, function (data) {
                  $('[id="2"]').text(data);
              });
          });
      });
 </script> 
 </body>
</html>
&#13;
&#13;
&#13;

最后我要做的是发送一个值&temp;&#39; temp&#39;按一下按钮&#39; stopButton&#39;到HTML页面。

1 个答案:

答案 0 :(得分:0)

如果你想从cheerio渲染html输出,cheerio描述了以下方式。

var cheerio = require('cheerio'),
    $ = cheerio.load('<h2 class="title">Hello world</h2>');

$('h2.title').text('Hello there!');
$('h2').addClass('welcome');

$.html(); // !!!You need this step!!!

然后在客户端,使用使用$('[id="2"]').html(data);

$('[id="2"]').text(data);实例