jQuery-在.serialize()中摆脱%5B%5D [英] JQuery - Getting rid of %5B%5D in .serialize()

查看:44
本文介绍了jQuery-在.serialize()中摆脱%5B%5D的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用AJAX提交序列化表格.传递给 action.php 的数据最终包含%5B%5D而不是[].无论如何都可以找回[],还是可以使用 action.php 中的相同方式(例如数组)来处理数据?

I'm using AJAX to submit a serialized form. The data passed on to the action.php ends up containing %5B%5D instead of []. Is there anyway of getting back the [], or will the data be able to be handled the same way (i.e. like arrays) in action.php?

该表格通过以下方式序列化:

The form is serialized via:

var form_data = $("#form").serialize();

然后我通过 $.ajax 发送它:

$.ajax({
    type: "POST",
    url: "action.php",
    data: {
        form_data: form_data,
        FrmSubmit: 'SubmitButton'
    },
    cache: true,
    success: function (html) {

        $("#show").html(html);
        alert("form success");
    }
});

传递给 action.php 的理想数据应该类似于: name = JohnSmith& color [] = blue& color [] = yellow& meal [] = chicken& meal[] = fish

The ideal data being passed to action.php should be something like: name=JohnSmith&color[]=blue&color[]=yellow&meal[]=chicken&meal[]=fish

我得到的是: name = JohnSmith& color%5B%5D = blue& color%5B%5D = yellow& %% 5B%5D = chicken& meal%5B%5D = fish

其他问题:我也尝试过.param(),但无法真正使接收到的数据成为正面或反面.每个字母最终都被编码为密钥.谁能阐明为什么会这样?

Additional question: I have also tried .param(), but couldn't really make heads or tails of the data received. Every letter ended up being encoded in a key. Could anyone shed light on why this might be?

推荐答案

因此,您正在做的是有效地对数据进行双序列化.

So what you're doing is effectively double-serializing the data.

在这里:

var form_data = $("#form").serialize();

然后再次在这里:

$.ajax({
    type: "POST",
    url: "action.php",
    data: {
        form_data: form_data,
        FrmSubmit: 'SubmitButton'
    },
    cache: true,
    success: function (html) {

        $("#rsvp_sub").html(html);
        alert("form success");
    }
});

当您将一个对象传递给 data 参数的 $.ajax 时,它会序列化并对其进行编码.

When you pass an object into $.ajax for the data argument, it serializes and encodes it.

所以...不要那样做.一种选择是执行此操作:

So...don't do that. One option is to do this:

var form_data = $("#form").serialize() + "&FrmSubmit=SubmitButton";
$.ajax({
    type: "POST",
    url: "action.php",
    data: form_data,
    cache: true,
    success: function (html) {

        $("#rsvp_sub").html(html);
        alert("form success");
    }
});

请注意,如果 FrmSubmit SubmitButton 包含除AZ,az,0-9(我是保守的)之外的任何内容,或者您​​不控制它们包含的内容,您想使用 encodeURIComponent :

Note that if either FrmSubmit or SubmitButton contained anything other than A-Z, a-z, 0-9 (I'm being conservative), or if you don't control what they contain, you'd want to use encodeURIComponent:

var form_data = $("#form").serialize() + "&" +
    encodeURIComponent('FrmSubmit') + "=" +
    encodeURIComponent('SubmitButton');

这篇关于jQuery-在.serialize()中摆脱%5B%5D的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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