简体   繁体   中英

Perform JavaScript on submit of form

I use a JavaScript to load new pages on my webpagepage. looks like this:

function loadpage(page,div) {
            $.get(page, function(data) {
                $(div).html(data)
            });
        };

So when i submit my form, I want to use that function to load the php-page you normally would set as your "action" attribute in the form-tag. So how do I get the form to POST or GET(doesen't really matter) all its content and use the function.

Now, when I write:

<form action="javascript:loadpage('bla.php','#content');" method="post">
...
</form>

it loads bla.php the way i want it to but no data is being passed byt the POST...

Is there a solution to this problem? Thank you very much in advance.

参见form.onsubmit事件

Using your method, you would do it as follows:

Javascript:

function loadpage(page, div, form) {
    var GETdata = '';

    if ( form ) GETdata = $(form).serialize();

    $.get(page, GETdata, function(data) {
        $(div).html(data)
    });
};

HTML:

<form action="javascript:loadpage('bla.php','#content', this);" method="post">
...
</form>

A better way would be to use non-obtrusive Javascript. Remove the inline javascript:

<form id="theForm" action="" method="post">
...
</form>

and bind your event handler from within your Javascript code:

$('#theForm').submit(function(e){
    e.preventDefault();
    loadpage('bla.php','#content', this);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM