JQuery - 附加到序列化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8289349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:17:53  来源:igfitidea点击:

JQuery - Appending to Serialize

jqueryserialization

提问by user1002039

I am trying to figure out how to append two more values to the serialize method in JQuery. I have the following code to submit a form with ajax and have two more variables that I would like to append:

我想弄清楚如何向 JQuery 中的序列化方法追加两个值。我有以下代码可以使用 ajax 提交表单,并且还有两个我想附加的变量:

Thank you!

谢谢!

    ...
    var formData = $('#contact_form').serialize();
    submitForm(formData);

    // -----------------------------------------------
    // AJAX FORM SUBMIT
    // -----------------------------------------------
    function submitForm(formData){
        $.ajax({    
            type: 'POST',
            url: 'contact.php',
            data: formData,
            dataType: 'json',
            cache: false,
            timeout: 7000,
            success: function(data) {
                // display success message
                response(data.msg,'show');
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                ...
            },              
            complete: function(XMLHttpRequest, status) { 
                ...
            }
        });
    }

回答by Manse

If you change serialize()to serializeArray()you can push values into the array :

如果您更改serialize()serializeArray()您可以将值推入数组:

var formData = $('#contact_form').serializeArray();
formData.push({ name: "<something>", value: "<somevalue>" });
submitForm(formData);

The data can still be sent in the same way as you would with the serialize()method, using the $.ajax()method

数据仍然可以以与使用serialize()方法相同的方式发送,使用$.ajax()方法

回答by Sal

You can add new values by appending to your variable:

您可以通过附加到变量来添加新值:

formData += '&var1=blah&var2=blah';