简体   繁体   中英

Node.js Ajax Call Modify JSON Data

This is my first time using node.js I have managed to successfully send json data to my node.js server but I can't figure out how to pass the json data into a function inside the server and modify it. My applications intention is a simple timer to showcase how node.js works. If someone could give me some assistance with this it would be greatly appreciated.

Update, I was able to get my code to work in the console the timer is now counting but it is not writing back to the html page.

Below is my code,

 function incrementTimer(time) { if (time.second != 60) { time.second +=1; } else { time.second = 0; if (time.minute != 60) { time.minute +=1; } else { time.minute = 0; time.hour +=1; } } return time; } var port = 8080; var http = require("http"); var server = http.createServer(); server.on('request', request); server.listen(port); function request(request, response) { console.log('Request Recieved'); var store = ""; request.on('data', function(data) { store += data; }); store = incrementTimer(store); request.on('end', function() { console.log(store); var storeObj = JSON.parse(store); incrementTimer(storeObj); response.setHeader("Content-Type", "text/json"); response.setHeader("Access-Control-Allow-Origin", "*"); response.end(JSON.stringify(storeObj) }); } console.log('Server Started'); 
 <html> <head> <title>Node.js Demo</title> </head> <body> <h1>Demo of Node.JS</h1> <div id="timer"></div> <button onclick="startTimer(0,0,0)">Start Timer</button> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script> <script> function startTimer(s,m,h) { $.ajax({ type: "POST", url: "http://localhost:8080", crossDomain: true, dataType: "json", data:JSON.stringify({second: s, minute: m, hour: h}), success: function (data) { $('#timer').text(data.hour + ":" + data.minute + ":" + data.second); setTimeout(function(){ startTimer(data.second,data.minute,data.hour); }, 1000); }, error: function (xhr, ajaxOptions, thrownError) { alert(xhr.status); alert(thrownError); } }); } </script> </body> </html> 

我试图写一个id是一个非常简单的错误,但这是一个类。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM