Ajax请求正在不断发送,我不确定为什么
在代码的多个区域中放置false。
//when user clicks on create channel
document.querySelector('#add-channel').onclick = () => {
// pop up modal
modal1.style.display = "block";
// Initialize new request
document.querySelector('#form1').onsubmit = () => {
const request = new XMLHttpRequest();
const chatroom = document.querySelector('#chatroom').value;
const username = localStorage.getItem('name');
request.open('POST', '/add_chatroom');
// Callback function for when request completes
request.onload = () => {
// Extract JSON data from request
const data = JSON.parse(request.responseText);
// Update the result div
if (data.success) {
// get the data that was returned.
// add it back to the list
document.querySelector('#contacts').append(li);
}
else {
alert('chatroom already exists');
}
}
// add data to send to the server
const data = new FormData();
data.append('chatroom', chatroom);
data.append('username', username);
// Send request
request.send(data);
return false;
};
};
即使我仅在提交ID为#form1的表单时才触发该事件,但每次单击ok时,发布请求都不会停止。即使我单击“确定”警报,它也会触发。
答案 0 :(得分:0)
我最终将浏览器从Firefox更改为Microsoft Edge,以解决onsubmit重新运行问题,这是我所不知道的。