Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

javascript - get req.body.task is undefined after click on checkbox

When I have click on checkbox then req.body.task return undefined.

<input type="checkbox" name="task" autocomplete="off" checked="" onchange="onToDochange({{id}})">

Perform on change function which return id of checked or unchecked checkbox.

function onToDochange(id) {
    // console.log(id);
    fetch('/checkbox', {
       method: 'POST',
       body: JSON.stringify({global: id})
     })
    .then(res=>res.json())
    .then(res => console.log(res));
};

Routing

app.post('/checkbox', (req, res) => {
    console.log(req.body.task);
});

Working with expressJS nodeJs template engine handlebars

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The way you are sending id is not correct.

What you need to do is bind your onclick event handler function and with that event get id or value whatever you need in the event handler function. Also you are setting id to a key called global but you are accessing with req.body.task which is not correct.

Workig code is available in codesandbox

Check below code for better understanding of how to send id and access the id in router.

<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));
};

Routing

app.post('/checkbox', (req, res) => {
    console.log(req.body.id);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...