I'm new to node.js. Now I'm trying to write a simple website where users can input something for the server to process, and receive a result, e.g. search for something.
I try to implement it as follows:
write the
index.html
write the
server.js
, it creates a server, and display the index page usingvar index = fs.readFileSync('index.html'); response.end(index);
add ajax codes in index.html, to receive input from users and send it to the server
the last step will be adding codes in server.js, which processes the request and send a result to ajax to display it.
My question is about step 4. In the server.js, when it receives ajax request, should it somehow add the result to the index.html file, and send back usingresponse.end(index)
, OR send back only the result? If the latter one, which I tried, it will send both the index.html page and the result. But I only want the result.
Below is the two files index.html
and server.js
:
index.js
<!DOCTYPE html>
<html>
<!-- Client search using Ajax -->
<head>
<title>live search</title>
<script>
function getResults(query) {
if (query.length===0) {
document.getElementById("results").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","http://127.0.0.1:2000/search?"+query,true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("results").innerHTML=xmlhttp.responseText;
}
};
xmlhttp.send();
}
</script>
</head>
<body>
<hr>
<input type="text" id="search" onkeyup="getResults(this.value)"/>
<br>
<div id="results">
</div>
</body>
</html>
server.js
var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html');
var url = require('url');
http.createServer(function (req, res) {
res.writeHead(200, {'ContentType': 'text/html'});
res.end(index);
//codes for request processing
result="";
var path = url.parse(req.url).pathname;
console.log(path);
if (path.length!==0) {
result = "I'm the result";
}
res.write(result);
}).listen(2000);