【发布时间】:2016-01-14 03:05:42
【问题描述】:
我编写了一个非常简单的 Express NodeJS 应用程序,它从表单中的用户读取数据并发送到服务器。服务器进行一些操作并将新字符串返回到同一页面。但是,要将新数据返回到当前加载的页面,我必须重新渲染页面。我只想通过从节点 js 发送字符串来更新字符串,而不是重新渲染整个页面。
我有以下问题:
- 如何从 NodeJS 服务器发送数据而不重新渲染整个页面?
-
为什么用
Post方法发送数据,在req.body.XXX提供数据,但用Get方法发送数据,返回undefined为req.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");
});
});
【问题讨论】:
-
你不只是在寻找常规的 ajax 吗?
-
另外,对于
GET请求,数据在req.query中 -
尝试将 socket.io 添加到您的应用程序中。它提供了向客户端发送数据的最简单方法,无需客户端多次请求。
-
@adeneo 请原谅我在 Web 开发方面的文盲,但我认为 ajax 是针对客户端的。那么如何使用ajax将数据从Server发送到客户端呢?
-
您正在将数据从表单提交到服务器,服务器对数据进行处理并在新页面中返回。这就是 ajax 的用例,它是它的确切用例,从客户端发送数据,向该请求返回数据等。或者您是否需要在客户端不要求的情况下将数据从服务器随机推送到客户端.
标签: javascript node.js express