2013-08-17 27 views
0

我是node.js開發中的新手,我有一個特殊的問題。我想創建一個帶有node.js的單頁web應用程序,用戶將提交請求數據,然後從imdb api獲取數據並將它們顯示在同一頁面上。我的代碼如下node.js ajax express在網頁上顯示寧靜的數據

server.js

#!/usr/bin/env node 
var express = require('express'); 
var app = express(); 

app.configure(function(){ 
app.set('views', __dirname + '/views'); 
app.set('view engine', 'jade'); 
app.use(express.bodyParser()); 
app.use(express.methodOverride()); 
app.use(app.router); 
app.use(express.static(__dirname + '/public')); 
}); 

var fs = require('fs'); 
var inputFile = fs.readFileSync('index.html').toString(); 
console.log(inputFile); 

app.get('/', function(request, response) { 
    response.send(inputFile); 
}); 

var port = process.env.PORT || 8080; 
app.listen(port, function() { 
    console.log("Listening on " + port); 
}) 




app.post('/', function(req, res){ 
if (req.body.mysearch == ""){ 
var search = "heroes"; 

}else{ 
    var search = req.body.mysearch; 
} 
    console.log(search); 
    var http = require('http'); 
    http.get("http://www.imdbapi.com/?t=" + search, function(res) { 
     console.log("Got response: " + res.statusCode); 
     var data = ''; 

     res.on('data', function (chunk){ 
     data += chunk; 
}) 
res.on('end',function(){ 
    // the whole of webpage data has been collected. parsing time! 
     var obj = JSON.parse(data); 
     console.log(obj.Title); 

    }) 
}).on('error', function(e) { 
    console.log("Got error: " + e.message); 
}) 
}); 

的index.html

 <html> 
    <head> 
     <meta charset="utf-8"> 
     <title>Title of the document</title> 
    </head> 

     <body> 
      <form id="myform" method="post" action="/"enctype="application/x-www-form-urlencoded"> 
<input type="text" id="search" name="mysearch"> 
<input type="submit" id="mysubmit" value="Search IMDB"> 
      </form> 
      <div id="myTitle"> 
      </div> 
     </body> 
    </html> 

代碼迄今已成功地解析來自IMDB的數據並將其顯示在控制檯上。現在的問題是我會如何打印它們的網頁上(例如,在div標籤),無需重新加載頁面(AJAX)

回答

相關問題