Adding/push() Values to Ajax POST in jQuery serialize() or serializeArray()

前端 未结 2 1013
栀梦
栀梦 2021-01-05 07:52

jQuery

$(\'#speichern\').live(\'click\' , function () {
 //  [a]  var data_save = $(\'#form_rechn\').serializeArray();
    var data_save_ser         


        
相关标签:
2条回答
  • 2021-01-05 08:31

    You can combine both the forms and serializeArray

    $('#frm1, #frm2').serializeArray()
    
    0 讨论(0)
  • 2021-01-05 08:34

    It should look like this:

    $('#speichern').live('click' , function () {
        var data_save = $('#form_rechn').serializeArray();
        data_save.push({ name: "action", value: "save" });
        data_save.push({ name: "mysql", value: "update" });
        data_save.push({ name: "total", value: Number($('#grandTotal').text().replace(/EUR/g, "")) });
        $.ajax({ 
          type    : "POST",
          cache   : false,
          url     : 'invoice_new_action.php',
          data    : data_save,
          error   : function (xhr, ajaxOptions, thrownError){
             alert(xhr.status);
             alert(thrownError);
          },
          success : function(data) { 
             $.fancybox(data); 
          }
        });
    });
    

    What you want to push onto the array are objects in the form of {name: "name", value: "value"}, then they'll be serialized/encoded correctly. Option [a] (the corrected form of it) is generally much better than option [b], since [b] isn't property encoded, and will fail the moment any invalid character slips in there to mess up your variables. In this case, because you're in control of the appended content, you're safe...but it's best to go the route that always works: never creating your data argument as a string directly.


    As for the why [a] doesn't work:

    data_save[data_save.length] = {"name":"action","value":"save" },{"name":"total","value": Number($('#grandTotal').text().replace(/EUR/g, ""))};
    

    This isn't valid, you can't assign 2 things at once, you either need to do it like this:

    data_save[data_save.length] = {"name":"action","value":"save" };
    data_save[data_save.length] = {"name":"total","value": Number($('#grandTotal').text().replace(/EUR/g, ""))};
    

    or this (my preferred method, as used above):

    data_save.push({"name":"action","value":"save" });
    data_save.push({"name":"total","value": Number($('#grandTotal').text().replace(/EUR/g, ""))});
    

    ....or, use $.merge() (a bit more wasteful, but cleaner looking), like this:

    $.merge(data_save, [{"name":"action","value":"save" }, {"name":"total","value": Number($('#grandTotal').text().replace(/EUR/g, ""))}]);
    
    0 讨论(0)
提交回复
热议问题