javascript - 单击复选框后获取 req.body.task 未定义
问题描述
当我点击复选框然后 req.body.task return undefined
。
<input type="checkbox" name="task" autocomplete="off" checked="" onchange="onToDochange({{id}})">
执行更改功能,返回选中或未选中复选框的 id。
function onToDochange(id) {
// console.log(id);
fetch('/checkbox', {
method: 'POST',
body: JSON.stringify({global: id})
})
.then(res=>res.json())
.then(res => console.log(res));
};
路由
app.post('/checkbox', (req, res) => {
console.log(req.body.task);
});
使用 expressJS nodeJs 模板引擎把手
解决方案
您发送 id 的方式不正确。
您需要做的是绑定您的 onclick 事件处理函数,并使用该事件获取事件处理函数中所需的 id 或值。此外,您将 id 设置为一个名为 global 的键,但您正在使用不正确的 req.body.task 访问。
工作代码在代码沙箱中可用
检查下面的代码以更好地了解如何发送 id 和访问路由器中的 id。
<input type="checkbox" name="task" autocomplete="off" checked="" onclick='onToDochange(this)' value="task" id="2">
function onToDochange(event) {
// console.log(event.id);
fetch('/checkbox', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({"id": event.id})
})
.then(res=>res.json())
.then(res => console.log(res));
};
路由
app.post('/checkbox', (req, res) => {
console.log(req.body.id);
});
推荐阅读
- xamarin.forms.listview - 我正在尝试从安卓模拟器发送请求。但是应用程序没有提供正确的输出并在 client.sendasync 上中断
- angular - 如果在angular2中编辑后具有值,如何保持字段启用
- django - 芹菜看不到任务
- javascript - 如何根据条件创建一个新数组将元素定位在第一个位置?
- javascript - 如何操作谷歌图表以获取 haxis 中的随机图例
- html - 从表格行中的输入插入数据
- wso2 - WSO2 CEP 水平可扩展性
- c# - 将自定义 TypeConverter 限制为特定程序集
- node.js - Node.js & Sequelize:findAll 上的 res.json?
- c# - 从 vb.net DLL 到 ac# DLL 的后期绑定调用