【问题标题】:How to properly use AJAX with express如何正确使用 AJAX 和 express
【发布时间】:2016-08-22 21:21:22
【问题描述】:

我在 node js 中创建了一个 udp 客户端,它每 10 秒发送一个 udp 数据包。我想使用 ajax 来创建一个刷新按钮,当按下按钮时,客户端可以从 udp 获取最新消息。以下是我到目前为止所拥有的。任何帮助都会很好,如果这令人困惑,请告诉我

节点js

var PORT = 69;
var HOST = '192.168.0.136';
var dgram = require('dgram');
var message = new Buffer('10');

var client = dgram.createSocket('udp4');

setInterval(function() {
client.send(message, 0, message.length, PORT, HOST, function(err, bytes) {
  if (err) throw err;

});

},10000);

client.on('message', function (message) {
    var data= message.toString();
    console.log(data);
app.get('/', function(req, res) {
    //render index.ejs file
    res.render('index', {val:data});
});


app.get('/ajax', function(req, res) {
    res.send(data);
});

});

app.listen(3000, function(){
  console.log('listening on *:3000');
});

html

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="/public/request.js"></script>
</head>
<body>

<h1>Val: <span id="val"><%=val%></span></h1>

<button id="loadRequest">Refresh</button>

</body>
</html>

js $(函数(){ $('#loadRequest').click(function() { $.get('/ajax', function(res) { $('#val').append(res); }); }); });

我现在可以获取当前消息,但是当我按刷新时,它不会更新为新消息。我知道我的错误可能在 ajax 请求中,但我不知道从哪里开始修复它。

【问题讨论】:

    标签: javascript html ajax node.js udp


    【解决方案1】:

    您的 ajax 请求未发布任何数据,因此 req.body 为空。此外,req.body.ipreq.body.port 不会自动包含在内,因此您也必须将它们与响应一起发送。要获取主机和 IP,请参阅此 JSFiddle。您可以使用表单来获取值,使用函数自己创建它们,甚至对它们进行硬编码,但它们必须与 ajax 请求一起发送。尝试像这样格式化您的请求:

    $(function() {
      $('#loadRequest').click(function() {
        $.post('/output2', {
          number: 42, //post a hard coded value
          host: someVar, //post the value from a variable you create
          ip: $('#someInput').val() //post the value from a input
        }, function(res) {
          $('#val').text(res);
        });
      });
    })

    更新:

    来自SPO question:主机名是您的机器名称和域名的组合(例如 machinename.domain.com)。主机名的目的是可读性——它比 IP 地址更容易记住。所有主机名都解析为 IP 地址,因此在许多情况下,它们被谈论得好像它们是可互换的。

    数字是任何用作数字值的东西。如果请求不需要发送任何数据,您实际上不需要发送任何数据,您可以使用空对象{}(尽管如果是这种情况,您可能应该使用获取请求)。我不确定您为什么需要主机和 ip,我将它们包括在内是因为它们在您的原始代码中,我认为它们用于 sn-p 未包含的东西。如果您不需要它们,则不需要它们。

    您无需将键转换为字符串,但这不会造成任何伤害。 'number'number 都可以。它们只是成为您的req.body 中的键,任何其他键都将返回undefined。在上面的示例中,您的 req.body 将是这样的对象:

    {
     number: 42,
     host: theValueOfSomeVar, //if you send a variable it sends the value, not the variable itself
     ip: theValueOf$('#someInput').val()
    }
    

    然后在你的路线req.body.number === 42req.body.host === theValueOfSomeVarreq.body.ip === theValueOf$('#someInput').val()req.body.anyOtherKey === undefined

    我不是 100% 确定这会起作用,但我认为是这样......与其渲染数据并在每条消息上发送它,不如进行 30 次调用并将每条消息推送到一个数组中,然后将数组发送到前面结束并使用 jQuery 在您的成功回调中每 10 秒添加一条消息。

    新的 Node.js 代码(带有 client.on):

    app.post('/output2', function(req, res) {
      let HOST = 192.168.0.136;
      let PORT = 69;
      //Reading in the user's command, converting to hex
      let message = Buffer.from(42, 'hex'); //new Buffer(str[, encoding]) is deprecated
    
      //Sends packets to TFTP
    
      client.send(message, 0, message.length, PORT, HOST, function(err, bytes) {
        if (err) throw err;
      });
    
      client.on('message', function(message) {
        let msg = new Buffer(message, 'hex');
        res.send(msg);
      });
    });

    新的新jQuery:

    $(function() {
      $('#loadRequest').click(function() {
        var count = 0;
        var requestLoop = setInterval(function() {
          $.post('/output2', {
            number: 42, //post a hard coded value
            host: someVar, //post the value from a variable you create
            ip: $('#someInput').val() //post the value from a input
          }, function(res) {
            $('#val').append(res);
          });
    
          count++;
          if (count >= 30) {
            clearInterval(requestLoop);
          }
        }, 10000);
    
      });
    })

    【讨论】:

    • ip和host需要' '围起来吗?
    • @patidar 评论中没有足够的空间,所以我用你想要的信息编辑了我的答案:-)
    • 所以我更新了我的代码以包含你的代码,但我仍然很困惑。发送到 app.post() 方法的数字 42 也是如此。对不起,如果我是愚蠢的,但我很难理解它。
    • @patidar 你不傻,这东西令人困惑!是的,数字 42 作为发布请求的一部分发送到您的发布路线。 $.post() 方法接受多个参数,但只需要 url。这是模式:$.post( url [, data ] [, success ] [, dataType ] ) url 是您要发布到的路由,data 是将发送到 post 路由并成为节点路由中的 req.body 的对象或字符串,success 是一个函数,它需要一个表示来自服务器的响应对象的参数,dataType 是预期返回数据的类型。
    • @patidar 你可以阅读jQuery docs中的所有细节。
    猜你喜欢
    • 2021-04-19
    • 2015-11-10
    • 1970-01-01
    • 2019-09-01
    • 2020-09-12
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    • 2016-07-07
    相关资源
    最近更新 更多