开发者

Don't reload page when submitting form without jQuery

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);
开发者_高级运维

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;.

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?


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

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

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.

By the way, using jQuery it would be:

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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜