如何修改 jQuery 中的序列化表单数据? [英] How do I modify serialized form data in jQuery?

查看:20
本文介绍了如何修改 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 然后添加到数组中并使用 jQuery.param 将结果转换为查询字符串,但这似乎有很长的路要走'圆:

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.

这篇关于如何修改 jQuery 中的序列化表单数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆