jQuery post() with serialize and array of data

心不动则不痛 提交于 2019-11-30 21:27:08

I had a similar problem when passing arrays.

Instead of using $.post use $.ajax and set the traditional option = true ...

$.ajax({
    type: "POST",
    url: "Work/",
    traditional: true,
    data: { collection: ['a','b','c'] }
});

The traditional: true option is important

I banged my head against this wall for months with the regular .ajax() call.

I eventually found out that you need to set traditional: true in the params list for $.ajax(). (see the "traditional" heading here: http://api.jquery.com/jQuery.ajax/)

Since there is no params list for $.post(), I'm not sure you can do this with $.post(). But it's not much more code to use $.ajax().

                var model = $('#myForm').serializeArray();

                $.map(['a', 'b', 'c'], function (val, i) {
                    return model.push({ "name": "collection[" + i + "]", "value": val });
                });

                $.post("/Work/Post", model);
                //OR
                $.post("/Work/Post", model, function (data) {
                    //After Success
                });

The following worked for me. You can use serializeArray() serializeJSON() as below and set that to the data element. Observe the formData variable.

var formData = $('#inputForm').serializeJSON();
$.ajax({
    type : "POST",
    url: server_side_url,
    cache:false,
    traditional: true,
    data: formData,
    dataType: "json",
    success: function(data, textStatus, jqXHR){
        console.log("successfully processed.");
    },
    error: function(xhr,status,error){
        console.log("error occurred.");
    }
}); 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!