Jquery Post multidimensional array via $.Ajax

梦想的初衷 提交于 2020-01-02 09:11:16

问题


I am trying to post an ajax call as if it were the following form element:

<input type="text" name="data[BlogPost][title]" />

But I'm not having any luck here is my source:

    $.ajax({
        url: "/add/",
        type: "POST",
        data: ( /* what do I do here */),
        success: function(msg){
            alert(msg);
        }
    });

I've tried nested objects but that only generates a server response like: array 'data' => string '[object Object]' (length=15)

Which does nobody any good!

Any thoughts?


回答1:


Just put the field name in quotes, also notice I am using an object literal for the data parameter {} vs the parens you had in your question:

$.ajax({
    url: "/add/",
    type: "POST",
    data: { 'data[BlogPost][title]':'My New Title'} ,
    success: function(msg){
        alert(msg);
    }
});



回答2:


Have you tried serialize()?

$.ajax({
    url: "/add/",
    type: "POST",
    data: $('#myForm').serialize(),
    success: function(msg){
        alert(msg);
    }
});

I'm not 100% sure it works on multidimensional arrays but it's worth a shot.




回答3:


My guess, [..] square brackets are not valid characters for names of input elements?

Correct me if I'm wrong.

Update: Oops, ok so I'm wrong. Will leave this here anyway as a 'learning' info. For others like me :)



来源:https://stackoverflow.com/questions/2032044/jquery-post-multidimensional-array-via-ajax

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