简体   繁体   中英

Push an array onto existing form data for an AJAX call

I'm trying to append/push an existing array of strings onto existing html form data. Posting manually like this works fine:

$(function () {
        $('#submitForm').submit(function (evt) {
            //prevent the browsers default function
            evt.preventDefault();
            //grab the form and wrap it with jQuery
            var $form = $(this);
            //if client side validation fails, don't do anything
            if (!$form.valid()) return;
$.ajax({
                type: $form.prop('method'),
                url: $form.prop('action'),
                data: {
                    'ListRFID': GetSelectedItems(), 
                    'Printer': 'e38911b2-1a2d-e311-be86-c8f7334c3af0',
                    'ExtraLine1': ''},
                dataType: "json",
                traditional: true,
                success: function (response) {
                    document.body.innerHTML = response;
                }
            });
    });
});

If I do the following and replace AJAX's data with it, it does not work. It sends an undefined variable in lieu of ListRFID.

var temp = { 'ListRFID': GetSelectedItems() };
var data = $form.serializeArray();
data.push(temp);
//AJAX data: data,

The following almost works but sends the post data as ListRFID[]: instead of ListRFID:

data: $form.serialize() + '&' + $.param({ 'ListRFID': GetSelectedItems() }),

Anyone know the proper Javascript methods to get this to work? Much appreciated.

It seems like what you want to do is merge the contents of two or more objects together.

So in your Ajax call data property would be:

data: $.extend( {}, $form.serializeArray(), { 'ListRFID': GetSelectedItems() } ),

Read more here: http://api.jquery.com/jQuery.extend/

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