【问题标题】:Node.js Ajax Call Modify JSON DataNode.js Ajax 调用修改 JSON 数据
【发布时间】:2016-04-09 02:44:04
【问题描述】:

这是我第一次使用 node.js,我成功地将 json 数据发送到我的 node.js 服务器,但我不知道如何将 json 数据传递到服务器内部的函数中并对其进行修改。我的应用程序意图是一个简单的计时器来展示 node.js 是如何工作的。如果有人可以在这方面给我一些帮助,将不胜感激。

更新,我能够让我的代码在控制台中工作,计时器现在正在计数,但它没有写回 html 页面。

下面是我的代码,

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>

【问题讨论】:

  • 这可能是由成功消息中发生的递归引起的,DOM在退出成功消息之后才被写入吗?

标签: javascript json ajax node.js


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    相关资源
    最近更新 更多