2015-07-28 62 views
0

我試圖在node.js上使用ejs作爲我的模板來運行Cheerio。每當我運行服務器時,我都會在'console.log'處得到'undefined'。以下是我的代碼。在Node.js上使用Cheerio時未定義

服務器側 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){ 
 
\t console.log(temp); 
 
\t 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>

在端WHA我希望做的是在按下「stopButton」按鈕時向HTML頁面發送「temp」值。

回答

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"]').text(data);

$('[id="2"]').html(data);實例