简体   繁体   English

JavaScript 中是否有办法检索 * 将 * 与表单一起发送而不提交的表单数据?

[英]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...如果我有一个 HTML 表格,假设...

<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 ...然后我使用 jQuery 来响应表单提交事件,例如

$('#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).现在假设我想以 AJAX 调用的形式提交表单,而不是以“传统”方式(作为新页面)实际提交。 Is there an easy way to get a JS object containing the data that would be sent, which I can pass into $.post() ?有没有一种简单的方法来获取包含将要发送的数据的 JS object,我可以将其传递给$.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() .由于您已经在使用 jQuery,请使用jQuery.serialize()

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

See the serialize() method.请参阅serialize()方法。

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

    return false;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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