我遇到一个问题,我只想在第一次加载页面时才运行load_mailbox('inbox')
,但是在提交表单时,我想使用其他参数('sent')来加载邮箱,如下代码所示。但是我认为正在发生的事情是,由于load_mailbox('inbox')
位于DOMContentLoaded事件侦听器内部,因此即使load_mailbox('sent')
完成加载后它仍在运行,任何人都可以想到一种阻止它进行操作的方法那么,还是该问题的另一种解决方案?
代码:
document.addEventListener('DOMContentLoaded', function() {
// By default, load the inbox
load_mailbox('inbox');
document.querySelector('#compose-form').onsubmit = function() {
//Declaring email variables
const recipients = document.querySelector('#compose-recipients').value
const subject = document.querySelector('#compose-subject').value
const body = document.querySelector('#compose-body').value
//Making API request
fetch('/emails', {
method: 'POST',
body: JSON.stringify({
recipients: recipients,
subject: subject,
body: body
})
})
.then(response => response.json())
.then(result => {
console.log(result);
load_mailbox('sent');
});
}
});
答案 0 :(得分:0)
如@PatrickEvans所述,问题在于该表单正在执行其默认操作,该操作是重新加载url,从而防止其返回false;在提交回调函数的末尾修复了它!
现在事件监听器及其回调如下所示:
document.querySelector('#compose-form').onsubmit = function() {
//Declaring email variables
const recipients = document.querySelector('#compose-recipients').value
const subject = document.querySelector('#compose-subject').value
const body = document.querySelector('#compose-body').value
//Making API request
fetch('/emails', {
method: 'POST',
body: JSON.stringify({
recipients: recipients,
subject: subject,
body: body
})
})
.then(response => response.json())
.then(result => {
console.log(result);
load_mailbox('sent');
});
return false;
}