req.body 只适用于表单? node.js
req.body only works on form? node.js
如何使用正文解析器库中的 req.body
如何获取 p 、按钮或输入以外的任何其他 html 标签的值?
test.ejs:
<button name="button">1</button>
<p name="p">This value needs to be changed</p>
routes.js:
// Assume that body-parser has been configured
router.post('/testRoute', function(req, res) {
button = req.body.button;
pTag = req.body.p;
/// Its not working :(
})
如何获取按钮或 p 标签的值?我需要做一些数据操作。
看,
req.body
与 html 的 body
不同。只能序列化表单元素以将数据发送回服务器,或者如果您从客户端使用 ajax,则可以定位特定元素以将其发送回服务器。
使用 ajax (因为 jQuery 被标记) 使用 submit
事件:
$('#formID').submit(function(e){
e.preventDefault(); // <----stops the form to get submitted
$.ajax({
url:'/testRoute',
data:{
button:$('button[name="button"]').attr('name'), // <---send button name
p :$('p[name="p"]').text() // send the p's text.
},
success:function(data){
console.log(data); // logs the response from the server.
},
error:function(){}
});
});
在 <p>
元素上使用 name
属性没有任何意义,您可以添加 class 名称:
<p class="p">This value needs to be changed</p>
然后在数据中您可以更改为 class 选择器:
data:{
button:$('button[name="button"]').attr('name'), // <---send button name
p :$('.p').text() // send the p's text.
},
如何使用正文解析器库中的 req.body
如何获取 p 、按钮或输入以外的任何其他 html 标签的值?
test.ejs:
<button name="button">1</button>
<p name="p">This value needs to be changed</p>
routes.js:
// Assume that body-parser has been configured
router.post('/testRoute', function(req, res) {
button = req.body.button;
pTag = req.body.p;
/// Its not working :(
})
如何获取按钮或 p 标签的值?我需要做一些数据操作。
看,
req.body
与 html 的 body
不同。只能序列化表单元素以将数据发送回服务器,或者如果您从客户端使用 ajax,则可以定位特定元素以将其发送回服务器。
使用 ajax (因为 jQuery 被标记) 使用 submit
事件:
$('#formID').submit(function(e){
e.preventDefault(); // <----stops the form to get submitted
$.ajax({
url:'/testRoute',
data:{
button:$('button[name="button"]').attr('name'), // <---send button name
p :$('p[name="p"]').text() // send the p's text.
},
success:function(data){
console.log(data); // logs the response from the server.
},
error:function(){}
});
});
在 <p>
元素上使用 name
属性没有任何意义,您可以添加 class 名称:
<p class="p">This value needs to be changed</p>
然后在数据中您可以更改为 class 选择器:
data:{
button:$('button[name="button"]').attr('name'), // <---send button name
p :$('.p').text() // send the p's text.
},