简体   繁体   中英

Is there a way in JavaScript to retrieve the form data that *would* be sent with a form without submitting it?

If I have an HTML form, let's say...

<form id='myform'>
    <input type='hidden' name='x' value='y'>
    <input type='text' name='something' value='Type something in here.'>
    <input type='submit' value='Submit'>
</form>

... and then I use jQuery to respond to the form submission event, eg

$('#myform').submit(function() {
    ...
    return false;
});

Now suppose I want to submit the form as an AJAX call instead of actually submitting it the “traditional” way (as a new page). Is there an easy way to get a JS object containing the data that would be sent, which I can pass into $.post() ? So in the above example it would look something like...

{
    x: 'y',
    something: 'Type something in here.'
}

or do I have to bake my own?

As you're already using jQuery, use jQuery.serialize() .

$('#myform').submit(function() {
    var $form = $(this);
    var data = $form.serialize();
    // ...
});

See the serialize() method.

$('#myform').submit(function() {
    jQuery.ajax({
        url: this.action,
        type: this.method,
        data: $(this).serialize(),
        success: function () {
           //
        }
    });

    return false;
});

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