我的快递服务器,deliverCard()
方法提供了一些键/值对。
app.get('/', (req, res) => {
let card = deck.deliverCard();
console.log('get', card)
res.render('layout.ejs', {element:card});
});
app.post('/', (req, res) => {
let card = deck.deliverCard();
console.log('post', card);
res.json(card);
});
XMLHttpRequest
:
function updateCard(value) {
let request = new XMLHttpRequest();
let params = JSON.stringify({learned: value});
request.onreadystatechange = () => {
if (request.readyState === 4 && request.status === 200) {
// Do a thing.
} else {
console.log('Status ' + request.status + ' text: ' + request.responseText);
}
}
request.open('POST', '/', true);
request.setRequestHeader('Content-type', 'application/json');
request.send(params);
}
close.addEventListener('click', function() {
value = checkbox[0].checked;
updateCard(value);
});
我从请求中找回了正确的请求主体,但由于某种原因,在服务器端,正在调用get回调函数。
开始和初始页面加载:
app listening on port 3000!
get { name: 'div',
description: 'Defines a generic block of content, that does not carry any semantic value. Used for layout elements like containers.' }
根据要求:
post { name: 'meter', description: 'Defines a horizontal meter.' }
get { name: 'progress', description: 'Defines a progress bar.' }
就好像页面在收到回复后重新加载一样。
答案 0 :(得分:0)
一旦我的问题得到了解答,我就找到了答案:How to avoid automatic page reload after XMLHttpRequest call?。从上面的代码中可以看出,我提交的是一个表单。为了防止表单提交中的默认操作,我这样做了:
close.addEventListener('click', function(e) {
e.preventDefault();
value = checkbox[0].checked;
updateCard(value);
});