jQuery post() with serialize and extra data

2019-01-02 14:43发布

Okay, so I'm trying to find out if it's possible to post serialize() and other data that's outside the form.

Here's what I though would work, but it only sends 'wordlist' and not the form data.

$.post("page.php",( $('#myForm').serialize(), { 'wordlist': wordlist }));

Anyone have any ideas?

9条回答
冷夜・残月
2楼-- · 2019-01-02 15:25

Try $.param

$.post("page.php",( $('#myForm').serialize()+'&'+$.param({ 'wordlist': wordlist })));
查看更多
高级女魔头
3楼-- · 2019-01-02 15:27

I like to keep objects as objects and not do any crazy type-shifting. Here's my way

var post_vars = $('#my-form').serializeArray();
$.ajax({
  url: '//site.com/script.php',
  method: 'POST',
  data: post_vars,
  complete: function() {
    $.ajax({
      url: '//site.com/script2.php',
      method: 'POST',
      data: post_vars.concat({
        name: 'EXTRA_VAR',
        value: 'WOW THIS WORKS!'
      })
    });
  }
});

if you can't see from above I used the .concat function and passed in an object with the post variable as 'name' and the value as 'value'!

Hope this helps.

查看更多
冷夜・残月
4楼-- · 2019-01-02 15:31

You could have the form contain the additional data as hidden fields which you would set right before sending the AJAX request to the corresponding values.

Another possibility consists into using this little gem to serialize your form into a javascript object (instead of string) and add the missing data:

var data = $('#myForm').serializeObject();
// now add some additional stuff
data['wordlist'] = wordlist;
$.post('/page.php', data);
查看更多
登录 后发表回答