【问题标题】:Undefined while using Cheerio on Node.js在 Node.js 上使用 Cheerio 时未定义
【发布时间】:2015-07-28 17:06:10
【问题描述】:

我正在尝试以 ejs 作为我的模板在 node.js 上运行 Cheerio。每当我运行服务器时,我都会在“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>

最后,我希望在按下按钮“stopButton”时向 HTML 页面发送一个值“temp”。

【问题讨论】:

    标签: node.js undefined ejs cheerio


    【解决方案1】:

    如果你想从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);的实例

    【讨论】:

      猜你喜欢
      • 2018-11-14
      • 2015-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-07
      • 1970-01-01
      • 2016-07-04
      相关资源
      最近更新 更多