开发者

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, e.g.

$('#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 s开发者_StackOverflowomething in here.'
}

or do I have to bake my own?


See the serialize() method.

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

    return false;
});


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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜