簡體   English   中英

從NodeJS發送數據而不重新渲染整個頁面?

[英]Sending data from NodeJS without re-rendering the whole page?

我編寫了一個非常簡單的Express NodeJS應用程序,它從表單中的用戶讀取數據並發送到服務器。 服務器執行一些操作並將新字符串返回到同一頁面。 但是,為了將新數據返回到當前加載的頁面,我必須重新呈現頁面。 我想通過從節點js發送字符串來更新字符串,而不是重新呈現整個頁面。

我有以下問題:

  • 如何在不重新渲染整個頁面的情況下從NodeJS服務器發送數據?
  • 為什么使用Post方法發送數據,在req.body.XXX提供數據但是使用Get方法發送數據,為req.body.XXX返回undefined

      <html> <head> <title><%= title %></title> <link rel='stylesheet' href='/stylesheets/style.css' /> </head> <body> <h1><%= title %></h1> <p>Welcome to <%= title %></p> <form id="myForm" action = "http://localhost:3000/testing" method="post"> Enter Url: <input type="text" name="urlEditText"/> <br /> <br /> Shortened Url:<%= shortenedUrl %> <br /> <br /> <input id="myButton" type="button" value="Submit" /> </form> </body> </html> 

index.js:

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express', shortenedUrl: ''});
    console.log("hello inside index.js method 0");
});


// passing an updated string back to the page
router.post('/yolo', function(req, res, next) {
    res.render('index', { title: 'NewTitle', shortenedUrl: req.body.urlEditText});
    console.log("hello inside index.js method 1");
});

編輯:

用於提交的JQuery腳本:

 $(document).ready(function() {
    $("#myButton").bind('click', function() {

      event.preventDefault();
      $("#myForm").submit(function() {
         document.write("button clicked calling yolo script");
      });

      $.post('/yolo', function() {
        document.write("button clicked calling yolo script");
        alert("yolo");
      });

    });

我建議使用像socket.io這樣的東西,這樣你就可以從服務器發送和接收數據,而無需重新加載頁面。 以下是他們網站的一個簡單示例:

服務器(app.js)

var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');

app.listen(80);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

客戶端(index.html)

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io('http://localhost');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
</script>

res.render僅用於呈現頁面。 在你的情況下,你很可能需要res.json({title: 'newTitle', ...})

至於你的第二個問題, req.body只填充了POSTPUT請求的數據。 對於GET您可以依賴req.queryreq.params具體取決於您組織API路線的方式

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM