[英]Correct Approach for Serving Javascript Files via Node.js Ajax?
I am trying to write a node application which serves crjavascript code to a static webpage. 我正在尝试编写一个将crjavascript代码提供给静态网页的节点应用程序。 The code would then be evaluated in the webpage.
然后,将在网页中评估代码。 Similar to this example , but with node instead of php.
与此示例类似,但使用node而不是php。 Server application looks like this:
服务器应用程序如下所示:
// 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/");
While client code looks like this: 虽然客户端代码如下所示:
<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 currently contains one line alert('hello world')
. example.js当前包含一行
alert('hello world')
。 The idea would be to send this line of code to index.html using the ajax query and then run it. 想法是使用ajax查询将这行代码发送到index.html,然后运行它。 However, I keep getting errors based on this line because of the ungainly mess of apostrophes and brackets:
但是,由于撇号和方括号的混乱情况,我一直在基于此行出现错误:
res.end('_js(\'{"message": " ' + js + '"}\')');
I was thinking there must be a better way to do this? 我以为必须有更好的方法来做到这一点?
如果您对通过ajax服务javascript并没有严格的要求,那么使用基于节点的Web服务器(例如expressjs)会更简单,这使您可以轻松地服务静态内容 。
Ok, solved by using res.end('_js(\\'{"message": " ' + escape(js) + '"}\\')');
好的,使用
res.end('_js(\\'{"message": " ' + escape(js) + '"}\\')');
on the server and eval(unescape(dataJson['message']))
on the client. 服务器上的
eval(unescape(dataJson['message']))
上的客户端。 Apologies for posting but I was getting nowhere for over an hour before figuring a solution... 抱歉致歉,但在找到解决方案之前一个多小时我都无处可去...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.