0

I need to display some values on a jsp page, grab input from user and send it back to a controller that is using Jackson to bind it to my backing data object. Several rows that I display on the screen are backed by an array and are created with <c:forEach> and I'm generating a path like "blobs[0].id" and "blobs[0].text". When I try to put them into the json object to be sent back to the controller by an ajax call, they aren't being added to the object properly. The property name ends up having "[0]" in the name instead of representing the object at that array index.

<script>
var formData = {};
formData.blobs = [];
formData.blobs[0] = {};
formData.blobs[0].id = "English";
formData.blobs[0].text = "Hello";
formData["blobs[1].id"] = "German";
formData["blobs[1].text"] = "Guten Tag";
console.log(formData);
</script>

ends up looking like {blobs: [0 : {id: "English", text: "Hello"}], blobs[1].id: "German", blobs[1].text: "Guten Tag"} instead of {blobs: [0 : {id: "English", text: "Hello"}, 1 : {id: "German", text: "Guten Tag"}]}

I am trying to assemble the model thusly:

<script>
function createModel() {
    var form = $("#theForm");
    var formData = {};
    $.each(form, function(i, v){
        var input = $(v);
        if (input.attr("name")) {
            formData[input.attr("name")] = input.val();
        }
    });
}
</script>
bcr666
  • 2,157
  • 1
  • 12
  • 23
  • Use `$("#theForm").serialize()` – Barmar Jul 18 '18 at 20:36
  • could you please carefully read your data structure, it's mess. it cannot produce both structures you mentioned. but this post will provide you all ways to collect form data: https://stackoverflow.com/questions/2276463/how-can-i-get-form-data-with-javascript-jquery – Dongdong Jul 18 '18 at 20:51

2 Answers2

0

Accessing obj["attr"] is an option to access an object's attribute, so obj["attr[1][22]"] will access an attribute called "attr[1][22]", while accessing obj["attr"][1][22] will access the second element of obj.attr, and the second element's 22th element as well..

The solution will be to access formData["blobs"][0].id or even formData["blobs"][0]["id"] you can format the string to your needs

Hagai Wild
  • 1,904
  • 11
  • 19
0

$('#yourform').serializeArray() returns an array:

[
  {"name":"foo","value":"1"},
  {"name":"bar","value":"xxx"},
  {"name":"this","value":"hi"}
]

$('#yourform').serialize() returns a string:

"foo=1&bar=xxx&this=hi"

so, in your case

var formData = {};
formData.blobs = [];
$('#yourform').serializeArray().forEach(function(blob){
  formData.blobs.push({
    id: blob.name,
    text: blob.value
  });
})
Dongdong
  • 2,208
  • 19
  • 28