JQuery - Getting rid of %5B%5D in .serialize()

妖精的绣舞 提交于 2021-01-27 07:36:59

问题


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

Then I send it through $.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");
    }
});

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

I am getting instead: name=JohnSmith&color%5B%5D=blue&color%5B%5D=yellow&meal%5B%5D=chicken&meal%5B%5D=fish

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?


回答1:


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

Once here:

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

And then again here:

$.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");
    }
});

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

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


来源:https://stackoverflow.com/questions/24048055/jquery-getting-rid-of-5b5d-in-serialize

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!