私は初心者ですから、ボタンをクリックするだけで完全に新しいページをブラウザに読み込むことができます。私は何かを試みたが、うまくいかない。ここにコードがあります。nodeJSを使用してブラウザに新しいページをロードする方法
NodeJSファイル:ここで
var http = require('http');
var fs= require('fs');
var htmlHome = "";
var htmlDemo = "";
htmlHome = fs.readFileSync("index.html");
htmlDemo = fs.readFileSync("demo.html");
//console.log(htmlHome.toString());
function onRequest(request, response)
{
console.log("A user made a request" + request.url);
if(request.url === "/")
{
response.writeHead(200, {"Context-Type": "text/plain"});
response.write(htmlHome);
response.end();
}
else if(request.url === "/demo.html")
{
console.log("DEMO")
response.writeHead(200, {"Context-Type": "text/plain"});
response.write(htmlDemo);
response.end();
}
}
http.createServer(onRequest).listen(80);
console.log("Server is running...")
が最初にロードするファイルindex.html
です:
<!DOCTYPE html>
<html>
<body>
<h2>Using the XMLHttpRequest Object</h2>
<div id="demo">
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</div>
<script>
function loadXMLDoc() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "demo.html", true);
xhttp.send();
}
</script>
</body>
</html>
そして、ここでは、私がボタンを押したときにロードするdemo.html
次のとおりです。
<!DOCTYPE html>
<html>
<body>
<h2>This is demo file!/h2>
</body>
</html>
ボタンを押したときを除いてすべてが機能します。新しいp年齢は上がらない。どうすればボタンを押すとdemo.html
ページがロードされるのですか?
NodeJSの "express"パッケージは静的ファイルをディスクから直接提供するのに非常に適しているので、ファイルをすべて読み込む必要はありません。 –
この回答に間違いがありますか? –