[英]Run Node.JS from page javascript button
我想做的是:用戶單擊網頁上的一個按鈕,它執行一個node.js腳本,該腳本在node.js頁面上執行服務器端操作。
示例:每次有人單擊頁面中的按鈕時,Node.js都會在服務器控制台上輸出一條消息。
到目前為止,我可以做的是:我可以展示一個帶有node.js + express的頁面。 我只是無法使服務器端操作發生。
<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>
謝謝!
您不需要使用快遞。 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>
server.js (Node.js)
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.