提交没有jQuery的表单时不要重新加载页面

问题描述:

我一直在尝试增强自己的JavaScript能力,因此我试图使用无jQuery的AJAX提交表单.出于某种原因,我似乎无法使用 addEventListener(); 来停止使用javascript提交表单.

I've been trying to enhance my javascript ability, hence I'm attempting to submit a form with AJAX sans jQuery. And for some reason it seems impossible for me to use addEventListener(); to stop form submission with javascript.

window.addEventListener('load', function(){
    document.forms[0].addEventListener('submit', function(){
        send();
        return false;
    }, false);
}, false);

此代码-独立于我尝试交换 return false; 和函数调用的顺序的任何方式-不会停止表单的提交,并且也不会返回send(); (自然返回false)或 returnValue = false; .

This code - independent of any way I attempt to swap order of the return false; and the function call - will not stop the form from submitting, and neither will return send(); (returning false, naturally) or returnValue=false;.

在内联事件侦听器中使用 return false; 时,我可以停止页面的重新加载和表单的默认提交方式,但是我必须使用它吗?有什么想法吗?

I'm able to stop the page from reloading and form from submitting the default way when using return false; within an inline event listener, but should I have to use that? Any thoughts?

您使用的是哪种浏览器?IE 9之前的IE中不支持addEventListener.

What browser are you using? addEventListener isn't supported in IE before IE 9.

此外,您还必须运行.preventDefault()和.stopPropagation().

Also, you have to run .preventDefault() and .stopPropagation().

还有一件事,在页面的所有内容(包括图像和所有内容)加载完毕之前,不会触发load事件,因此,在提交表单时,可能还没有注册处理程序.

And another thing, the load event won't fire before all of the contents of the page have loaded, including images and everything, so your handler may not be registered yet when you submit the form.

顺便说一句,使用jQuery将会是:

By the way, using jQuery it would be:

$(function(){
  $('form').submit(function(){
    send();
    return false;
  });
});

它将在DOM准备就绪后立即注册处理程序,并且可以在IE中运行.

It would register the handler as soon as the DOM is ready and it would work in IE.