Jac*_*ovi 3 jquery ejs node.js express
如何使用 body-parser 库中的 req.body
如何获得 p 、 button 或除输入以外的任何其他 html 标签的值?
测试.ejs:
<button name="button">1</button>
<p name="p">This value needs to be changed</p>
Run Code Online (Sandbox Code Playgroud)
路线.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 :(
})
Run Code Online (Sandbox Code Playgroud)
如何获取 button 或 p Tag 的值?我需要做一些数据操作。
看,
req.body不一样body的HTML。只有表单元素可以被序列化以将数据发送回服务器,或者如果您使用来自客户端的 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(){}
});
});
Run Code Online (Sandbox Code Playgroud)
这只是name在<p>元素上有一个属性没有任何意义,而您可以添加一个类名:
<p class="p">This value needs to be changed</p>
Run Code Online (Sandbox Code Playgroud)
然后在数据中您可以更改为类选择器:
data:{
button:$('button[name="button"]').attr('name'), // <---send button name
p :$('.p').text() // send the p's text.
},
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
794 次 |
| 最近记录: |