2013-02-09 59 views
1

我正在嘗試編寫一個節點應用程序,它將crjavascript代碼提供給一個靜態網頁。代碼將在網頁中進行評估。類似於this example,但用節點而不是php。服務器應用程序是這樣的:通過Node.js Ajax提供Javascript文件的正確方法?

// Load the http module to create an http server. 
var http = require('http'); 

// Configure our HTTP server 
var server = http.createServer(function (req, res) { 
    var js; 
    //send back all libraries 
    fs = require('fs'); 
    res.writeHead(200, {'Content-Type': 'text/plain'}); 
    //var paths = ['javascript.js']; 
    js = fs.readFileSync('example.js').toString(); 
    res.end('_js(\'{"message": " ' + js + '"}\')'); 
}); 

// Listen on port 8000, IP defaults to 127.0.0.1 
server.listen(8000); 

// put a message on the terminal 
console.log("Server running at http://127.0.0.1:8000/"); 

雖然客戶端代碼如下所示:

<html> 
<head> 
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no" charset="utf-8"/> 
    <script type="text/javascript" src="js/jquery.js"></script> 
    <script type="text/javascript"> 
     $(document).ready(function() { 
      $.ajax({ 
       url: 'http://127.0.0.1:8000/', 
       dataType: "jsonp", 
       jsonpCallback: "_js", 
       cache: false, 
       timeout: 20000, 
       success: function(data) { 
        var dataJson = JSON.parse(data); 
        console.log(dataJson['message']); 
        eval(dataJson['message']); 
        alert(test); 
       }, 
       error: function(jqXHR, textStatus, errorThrown) { 
        console.log('error ' + textStatus + " " + errorThrown); 
       } 
      }); 

     }); 
    </script> 
</head> 
<body> 
    <div class="container" id="container"></div> 
</body> 
</html> 

example.js目前包含一行alert('hello world')。這個想法是使用ajax查詢將這行代碼發送到index.html,然後運行它。不過,我不斷收到因爲撇號和括號的醜陋混亂的基礎上這一行錯誤:

​​

我想必須有一個更好的方式來做到這一點?

+0

res.json()如果你不介意使用Express,或者JSON.stringify? – 2013-02-09 23:09:24

回答

1

如果你沒有硬要求通過ajax服務的JavaScript,它會更簡單的使用節點例如expressjs,它可以讓您輕鬆服務static content

+0

謝謝。另外一個好主意,我會檢查出來。 – Owen 2013-02-12 03:35:02

0

好的,通過在服務器上使用res.end('_js(\'{"message": " ' + escape(js) + '"}\')');和在客戶端上使用eval(unescape(dataJson['message']))來解決。張貼道歉,但我得到了一個多小時才找到解決方案...

相關問題