如何在jQuery中修改序列化的表单数据?

84

我正在尝试使用AJAX提交表单,因此必须对数据进行序列化。但是我正在使用fckEditor,而jQuery不知道如何处理它,因此在序列化之后,我正在尝试手动修改值,但迄今为止没有成功...有什么想法吗?

if(content_val!=""){
    var values = $("#frmblog").serialize();
    values.content = content_val; //content_val is the manually fetched data which I am trying to insert into the serialized content.
    alert(content_val); alert(values);
}

为什么不在序列化之前插入它? - Adam Arold
问题在于,在序列化过程中,'content'键中设置了一些默认值,因此我不能只附加一个新值,而必须更新其中已有的值。 - Bluemagica
啊,那就不同了;请看我的更新答案。 - T.J. Crowder
5个回答

161

serialize 函数返回一个包含表单字段的 URL 编码字符串。如果您需要追加内容,可以使用标准的 URL 编码规则,例如:

var values = $("#frmblog").serialize();
values += "&content=" + encodeURIComponent(content_val);

上面的假设是在serialize调用后,values中将始终存在一个值;如果不一定如此,请确定在添加到values之前是否为空,然后决定是否使用&。或者,您也可以使用serializeArray,然后添加到数组中,并使用jQuery.param将结果转换为查询字符串,但这似乎是一个比较复杂的方法:
// You can also do this, but it seems a long way 'round
var values = $("#frmblog").serializeArray();
values.push({
    name: "content",
    value: content_val
});
values = jQuery.param(values);

更新:在稍后添加的评论中,您说:

问题是,在序列化过程中会设置“内容”键中的一些默认值,因此我不能只附加一个新值,而必须更新其中已有的值。

这改变了事情的情况。在URL编码的字符串中查找content很麻烦,因此我建议使用数组:

var values, index;

// Get the parameters as an array
values = $("#frmblog").serializeArray();

// Find and replace `content` if there
for (index = 0; index < values.length; ++index) {
    if (values[index].name == "content") {
        values[index].value = content_val;
        break;
    }
}

// Add it if it wasn't there
if (index >= values.length) {
    values.push({
        name: "content",
        value: content_val
    });
}

// Convert to URL-encoded string
values = jQuery.param(values);

您可能希望将此函数制作成可重复使用的功能。


8

现在使用 ES15,你可以使用这个替代当前已提交值的编辑功能(最短的一个)

var values = $("#frmblog").serializeArray();
values.find(input => input.name == 'content').value = content_val;
console.log(values);

或本地函数
var values = $("#frmblog").serializeArray();
values.find(function(input) { 
    return input.name == 'content';
}).value = content_val;
console.log(values);

4
这是一个完整的基于@T.J答案的jQuery插件。你可以调用它。
$('form#myForm').awesomeFormSerializer({
    foo: 'bar',
})

这将替换或添加参数'foo'的值为'bar'(或在对象中添加任何其他参数)

jQuery插件:

// Not builtin https://dev59.com/sW445IYBdhLWcg3wBlyJ#5075798
(function ( $ ) {
    // Pass an object of key/vals to override
    $.fn.awesomeFormSerializer = function(overrides) {
        // Get the parameters as an array
        var newParams = this.serializeArray();

        for(var key in overrides) {
            var newVal = overrides[key]
            // Find and replace `content` if there
            for (index = 0; index < newParams.length; ++index) {
                if (newParams[index].name == key) {
                    newParams[index].value = newVal;
                    break;
                }
            }

            // Add it if it wasn't there
            if (index >= newParams.length) {
                newParams.push({
                    name: key,
                    value: newVal
                });
            }
        }

        // Convert to URL-encoded string
        return $.param(newParams);
    }
}( jQuery ));

1
使用以下函数,这对我起作用了。
function(elementName,newVal)
{
    var postData = $("#formID").serialize();

var res = postData.split("&");
var str = "";

for(i=0;i<res.length;i++)
  {
    if(elementName == res[i].split("=")[0])
      {
        str += elementName + "=" + newVal+ "&";
      }
      else
      {
        str += res[i] + "&";
      }
  }
return str;
}

0

这是我如何完成你所需的

formData = $('#'+formID).find(":input")
                            .filter(function (i, item) {
                                if (item.name.includes('nameToBeChanged'))
                                {
                                    item.name = item.name.replace('nameToBeChanged', 'toChangedName');
                                    return true;
                                } else {
                                    return false;
                                }
                            }).serialize();

请注意,这将永久更改表单元素名称。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接