我正在尝试编写一个节点应用程序,为静态网页提供 crjavascript 代码。然后将在网页中评估代码。与此示例类似,但使用 node 而不是 php。服务器应用程序如下所示:
// 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,然后运行它。但是,由于撇号和括号的乱七八糟,我不断收到基于此行的错误:
res.end('_js(\'{"message": " ' + js + '"}\')');
我在想一定有更好的方法来做到这一点?