我已经编写了一个相当简单的Express NodeJS应用程序,该程序从用户在表单中输入的数据中读取并发送到服务器。服务器执行一些操作,并将新字符串返回给同一页。但是为了将新数据返回到当前加载的页面,我必须重新渲染页面。我想通过从Node JS发送字符串来更新字符串,而不是重新渲染整个页面。
我有以下问题:
我有以下问题:
- How to send data from NodeJS server without re-rendering the whole page?
Why does sending data with
Post
method, provides data inreq.body.XXX
but sending data withGet
method, returnsundefined
forreq.body.XXX
.<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");
});
});
GET
请求,数据位于req.query
中。 - adeneo