从页面javascript按钮运行Node.JS
我想做什么:用户单击网页上的按钮,它会执行node.js脚本,在node.js页面上执行服务器端操作 示例:每当有人单击页面中的按钮时,Node.js就会在服务器控制台上输出一条消息 到目前为止我能做什么:我可以展示一个带有node.js+express的页面。我就是不能让服务器端操作发生从页面javascript按钮运行Node.JS,javascript,node.js,Javascript,Node.js,我想做什么:用户单击网页上的按钮,它会执行node.js脚本,在node.js页面上执行服务器端操作 示例:每当有人单击页面中的按钮时,Node.js就会在服务器控制台上输出一条消息 到目前为止我能做什么:我可以展示一个带有node.js+express的页面。我就是不能让服务器端操作发生 <button type="button" onclick="testF()">Click</button> <script>
<button type="button" onclick="testF()">Click</button>
<script>
function testF(){
alert('Hello world!');
console.log('clicked!!'); //Id like this to show on the node.js console
}
</script>
点击
函数testF(){
警惕(“你好,世界!”);
console.log('clicked!!');//我想在node.js控制台上显示这个
}
谢谢大家! 您不需要使用express。Node.js非常简单 和其他成员一样,您必须使用AJAX,所以。。。jQuery也不是必需的 请看我为您编写的以下代码(请记住,我编写的代码非常弱,因为如果我编写的代码更安全,可能会比您预期的更大) test.html
<button type="button" onclick="testF()">Click</button>
<script>
function testF()
{
alert('Hello world!');
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("get", "/service");
xmlhttp.onreadystatechange = function()
{
// DONE
if (xmlhttp.readyState == 4)
{
switch(xmlhttp.status)
{
case 200:
alert("OK");
break;
case 404:
alert("Not Found");
break;
case 500:
alert("Internal Server Error");
break;
default:
alert("Unexpected Error. HTTP Status: " + xmlhttp.status);
}
}
};
xmlhttp.send();
}
</script>
您将需要ajax或重新加载页面,您需要使用
ajax
来完成这类工作。如果你对图书馆没有意见,这是事实上的选择。然后您需要使用express公开端点以接受http请求。谢谢!我也一直在试验socket.io,它似乎对我也有好处。
var nsHttp = require("http");
var nsUrl = require("url");
var nsPath = require("path");
var nsFs = require("fs");
var srv = nsHttp.createServer(function(req, res)
{
var pathname = nsUrl.parse(req.url).pathname;
// check URL to send the right response
switch(pathname)
{
case "/favicon.ico":
res.end();
break;
case "/":
HTTP_SendHtmlFile(res, nsPath.join(__dirname, "test.html"));
break;
case "/service":
console.log("clicked!");
HTTP_SendOK(res, "");
break;
default:
HTTP_SendNotFound(res);
}
});
// reads a file contents and sends, but if any error occur,
// sends a 500 HTTP Status Code (Internal Server Error)
function HTTP_SendHtmlFile(res, filepath)
{
nsFs.readFile(filepath, function(err, data) {
if (err) {
HTTP_SendInternalServerError(res);
return;
}
HTTP_SendOK(res, data);
});
}
function HTTP_SendOK(res, body)
{
res.writeHead(200, {"Content-type": "text/html"});
res.end(body);
}
function HTTP_SendInternalServerError(res)
{
res.writeHead(500, {"Content-type": "text/html"});
res.end();
}
function HTTP_SendNotFound(res)
{
res.writeHead(404, {"Content-type": "text/html"});
res.end();
}
srv.listen(8080);