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

问题描述:

我正在尝试使用AJAX提交表单,因此必须对数据进行序列化().但是我正在使用fckEditor,而jQuery不知道如何处理它,因此在序列化之后,我试图手动修改值,但到目前为止还没有运气...任何想法

I am trying to submit my form in AJAX, so I have to serialize() the data. But I am using fckEditor and 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

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

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

serialize returns 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.:

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

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

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

或者,如果愿意,可以使用 serializeArray ,然后将其添加到数组中并使用

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

// 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:

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

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"

这改变了一切.在URL编码的字符串中查找content是一件很痛苦的事情,所以我会选择数组:

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

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.