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:04

You can use serializeArray [docs] and add the additional data:

var data = $('#myForm').serializeArray();
data.push({name: 'wordlist', value: wordlist});

$.post("page.php", data);
查看更多
唯独是你
3楼-- · 2019-01-02 15:10
$.ajax({    
    type: 'POST',  
    url: 'test.php',  
    data:$("#Test-form").serialize(),  
    dataType:'json',
     beforeSend:function(xhr, settings){
     settings.data += '&moreinfo=MoreData';
     },
    success:function(data){
            //  json response  
    },
    error: function(data) { 
        // if error occured
    }
    });
查看更多
春风洒进眼中
4楼-- · 2019-01-02 15:10

In new version of jquery, could done it via following steps:

  • get param array via serializeArray()
  • call push() or similar methods to add additional params to the array,
  • call $.param(arr) to get serialized string, which could be used as jquery ajax's data param.

Example code:

var paramArr = $("#loginForm").serializeArray();
paramArr.push( {name:'size', value:7} );
$.post("rest/account/login", $.param(paramArr), function(result) {
    // ...
}
查看更多
孤独总比滥情好
5楼-- · 2019-01-02 15:14

An alternative solution, in case you are needing to do this on an ajax file upload:

var data = new FormData( $('#form')[0] ).append( 'name' , value );

OR even simpler.

$('form').on('submit',function(e){

    e.preventDefault();
    var data = new FormData( this ).append('name', value );

    // ... your ajax code here ...

    return false;

});
查看更多
裙下三千臣
6楼-- · 2019-01-02 15:19

You can use this

var data = $("#myForm").serialize();
data += '&moreinfo='+JSON.stringify(wordlist);
查看更多
弹指情弦暗扣
7楼-- · 2019-01-02 15:20

When you want to add a javascript object to the form data, you can use the following code

var data = {name1: 'value1', name2: 'value2'};
var postData = $('#my-form').serializeArray();
for (var key in data) {
    if (data.hasOwnProperty(key)) {
        postData.push({name:key, value:data[key]});
    }
}
$.post(url, postData, function(){});

Or if you add the method serializeObject(), you can do the following

var data = {name1: 'value1', name2: 'value2'};
var postData = $('#my-form').serializeObject();
$.extend(postData, data);
$.post(url, postData, function(){});
查看更多
登录 后发表回答