json
in Programming on NodeJS
NodeJS
html (request data to server with word) ->
server (receive data from server and return data) ->
html (receiver a data and print)
app.js
var express = require('express')
var app = express()
var bodyParser = require('body-parser')
app.listen(3000, function() {
console.log("start!! express server on port 3000");
});
app.use(express.static('public'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended:true}))
app.set('view engine', 'ejs')
// if html file call the /ajax_search
app.post ('/ajax_search', function(req, res){
console.log("Search Word is : "+req.body.searchword)
// data to send
var responseData = {'Searchword': req.body.searchword,
'Result1':'Result1','Result2':'Result2',
'Result3':'Result3','Result4':'Result4'}
//send data with json type
res.json(responseData)
});
form.html
<!DOCTYPE html>
<html>
<head>
<meta charset="uft-8">
<title>Search engine</title>
</head>
<body>
<form method="post">
<input type="text" name="searchword"><br/>
</form>
<button class="ajaxsend">Search</button>
<div class="result"></div>
<script>
// if user click the button
document.querySelector('.ajaxsend').addEventListener('click',function(){
// take data from the form
var inputdata = document.forms[0].elements[0].value;
// call the function (sendAjax)
sendAjax('http://127.0.0.1:3000/ajax_search',inputdata);
})
function sendAjax(url, data){
// packing the data with string type
var data = {'searchword' : data};
data = JSON.stringify(data);
var xhr = new XMLHttpRequest();
xhr.open('POST', url);
// declare the data is json type
xhr.setRequestHeader('Content-Type', "application/json");
// send a data
xhr.send(data);
// listen a event from the server.
xhr.addEventListener('load', function(){
// pasing from JSON type to string
var result = JSON.parse(xhr.responseText);
// Print a data with Ajax
for(var item in result){
document.querySelector(".result").innerHTML += item+" : "+result[item] +"<br>";
}
});
}
</script>
</body>
</html>