javascript 向 $form.serialize() ajax 帖子添加额外数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22208582/
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-10-27 22:41:26  来源:igfitidea点击:

add additional data to $form.serialize() ajax post?

javascriptjqueryajaxserialization

提问by user756659

I have the following snippet where I am serializing form data and posting it via ajax. I have come across a situation where I need to add additional data. In this case I need to add a comma separated array called 'selectedHours'. Is this possible?

我有以下代码段,我在其中序列化表单数据并通过 ajax 发布它。我遇到过需要添加额外数据的情况。在这种情况下,我需要添加一个名为“selectedHours”的逗号分隔数组。这可能吗?

I am creating 'selectedHours' through as shown below where it creates an array of list items with the class 'hour-selected'. There are no form values, inputs, etc used in this aspect.

我正在创建“selectedHours”,如下所示,它创建了一个带有“hour-selected”类的列表项数组。在这方面没有使用表单值、输入等。

var selectedHours = [];
$('.hour-selected').each(function(k,v) {
    selectedHours.push($(v).text());
});

$.ajax({ 
    type: 'post',
    url: '/process/somepage.php',
    data: $form.serialize(),
    dataType : 'json'
}).done(function (response) {
... and so on...

回答by Alessandro Minoccheri

try this:

试试这个:

$.ajax({ 
    type: 'post',
    url: '/process/somepage.php',
    data: $form.serialize() + '&hours=' + JSON.stringify(selectedHours),
    dataType : 'json'
}).done(function (response) {
... and so on...

data sended are just a URL encoded string. You can append other value with a simple concatenation.

发送的数据只是一个 URL 编码的字符串。您可以通过简单的连接附加其他值。

回答by Laef

Perhaps a better solution to this might be to use jQuery's serializeArray, as suggested by this answer:

也许更好的解决方案可能是使用 jQuery's serializeArray,正如这个答案所建议的那样

var data = $form.serializeArray();
data.push({name: 'hours', value: selectedHours});

$.post('/process/somepage.php', data).done(doSomething);

This solution might be preferable because it avoids manually constructing a serialized data string, instead opting to passing the data on for jQuery to deal with.

此解决方案可能更可取,因为它避免了手动构建序列化数据字符串,而是选择将数据传递给 jQuery 进行处理。