简体   繁体   中英

jQuery dynamic form submission

I can easily find how to submit an existing form using jQuery. But how can I, given a URL, and some parameters create and submit this form on the fly?

This sounds like a bad solution to a problem that can probably be better solved another way...

That being said, you can create a form and trigger the submit method on it easily enough:

$([
    '<form action="url.php" method="post">',
        '<input type="hidden" name="param1" value="foo"/>',
        '<input type="hidden" name="param1" value="foo"/>',
    '</form>'
].join('')).appendTo('body')[0].submit();

If you need to be able to specify the parameters and the url then you could write a function similar to this one:

function submitValues(url, params) {
    var form = [ '<form method="POST" action="', url, '">' ];

    for(var key in params) 
        form.push('<input type="hidden" name="', key, '" value="', params[key], '"/>');

    form.push('</form>');

    jQuery(form.join('')).appendTo('body')[0].submit();
}

and call it this way:

submitValues('url.php', { foo: 'bar', boo: 'far' });

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