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

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

How do I modify serialized form data in jQuery?

jqueryserializationfckeditor

提问by Bluemagica

I am trying to submit my form in AJAX, so I have to serialize() the data. But I am using fckEditorand jQuery doesn't know how to deal with it, so after the serialization, I am trying to manually modify the value, but no luck so far... any ideas

我试图在 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);
}

回答by T.J. Crowder

serializereturns a URL-encoded string containing the form fields. If you need to append to it, you do so using the standard URL-encoded string rules, e.g.:

serialize返回包含表单字段的 URL 编码字符串。如果您需要附加到它,您可以使用标准的 URL 编码字符串规则,例如:

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

(The above assumes there will always be one value in valuesafter the serializecall; if that's not necessarily true, determine whether to use &based on whether valuesis empty before you add to it.)

(以上假设调用values后总会有一个值serialize;如果这不一定正确,请在添加之前&根据是否values为空来确定是否使用。)

Alternately, if you like, you can use serializeArrayand then add to the array and use jQuery.paramto turn the result into a query string, but that seems a long way 'round:

或者,如果您愿意,您可以使用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);


Update: In a comment added later you said:

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

The problem is, there is some default values being set in the 'content' key during the serilization process, so I can't just attach a new value, I have to update the one already in it"

问题是,在序列化过程中,'content' 键中设置了一些默认值,所以我不能只附加一个新值,我必须更新其中已有的值”

That changes things. It's a pain to look for contentwithin the URL-encoded string, so I'd go with the array:

这会改变事情。content在 URL 编码的字符串中查找很痛苦,所以我会使用数组:

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);

You'd probably want to make this a reusable function.

你可能想让它成为一个可重用的函数。

回答by Cyril Duchon-Doris

Here is a full jquery plugin based on @T.J's answer. You can call

这是一个基于@TJ 答案的完整 jquery 插件。你可以打电话

$('form#myForm').awesomeFormSerializer({
    foo: 'bar',
})

Which will replace or add the param 'foo' with value 'bar' (or any other param you add in the object)

它将用值“bar”(或您在对象中添加的任何其他参数)替换或添加参数“foo”

jQuery plugin :

jQuery 插件:

// Not builtin http://stackoverflow.com/a/5075798/2832282
(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 ));

回答by Yanuarizal Kurnia

With ES15 now. You can use this instead one for editing current submitted value (the shortest one)

现在使用 ES15。您可以使用它来代替编辑当前提交的值(最短的一个)

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

or native function

或本机功能

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

回答by Malek Tubaisaht

use the following function it worked for me

使用以下对我有用的功能

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;
}