Не определено при использовании Cheerio на Node.js

Я пытаюсь запустить Cheerio на node.js с ejs в качестве шаблона. Всякий раз, когда я запускаю сервер, я получаю «неопределенное» в «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);

index.ejs

<!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>

В конце концов, я хочу отправить значение «temp» при нажатии кнопки «stopButton» на HTML-страницу.


person NeelDeveloper    schedule 28.07.2015    source источник


Ответы (1)


Если вы хотите отображать HTML-вывод из cheerio, 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);

person greenlikeorange    schedule 28.07.2015