【发布时间】:2019-02-16 01:14:48
【问题描述】:
当您希望在服务器端运行某些 javascript 函数时,无论是为了性能还是为了隐藏专有代码,当您的 HTML 文件访问外部 CSS 和 Javascript 时,您将如何使用 AJAX 请求发送和接收数据文件?
例如,将函数“secret_calculation”移动到 index.js(node.js 文件)中的正确方法是什么
index.js
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('app.html', function (err, data) {
if (err)
{
console.log(err);
}
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
fs.readFile('app.css', function (err, data) {
if (err)
{
console.log(err);
}
res.writeHead(200, {'Content-Type': 'text/css'});
res.write(data);
res.end();
});
fs.readFile('app.js', function (err, data){
if (err)
{
console.log(err);
}
res.writeHead(200, {'Content-Type': 'text/javascript'});
res.write(data);
res.end();
});
}).listen(8000);
app.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="app.css">
</head>
<body>
<input id="in_put" type="text" maxlength="3" size="5" oninput="this.value = this.value.replace(/[^0-9]/g, '');" >
<span> x 5 = </span><span id="answer"></span>
<br><br>
<input type="button" id="button1" value="Calculate">
<script src="app.js"></script>
</body>
</html>
app.css
span
{
color: red;
}
app.js
document.getElementById("button1").addEventListener("click", get_input);
function get_input()
{
user_input = parseInt(document.getElementById("in_put").value);
user_input = user_input || 0;
ans = document.getElementById("answer");
ans.innerHTML = secret_calculation(user_input);
}
function secret_calculation(num)
{
var result = num * 5;
return result;
}
我找到了 node.js AJAX 请求 here 的一个很好的例子,但是这篇文章不使用外部 css 和 javascript 文件
【问题讨论】:
标签: javascript html node.js ajax backend