Im currently trying to figure out how to work with a bidimensional array on Java that I generate on a JSP with JavaScript. The problem is that when I assign it to an existing property that is hidden on the form in order to be sent throught the request it generates a full string with all the values, like this:
function saveArray(){
var array= frames['myFrame'].array;
//this comes from a child frame and its perfectly ok, works
//fine on a 2 dimension array
document.forms[0].arrayHiddenProperty.value = array;
}
How can I, either make a field on a html form to be an array (i donth think its possible), or to send the full array to my Java backend? Project is using Struts so this is an Action class. Thanks guys.
Formdata accept only string types, so when the type is not string is converted automatically into a string type, however you can append on a formdata a key more than just one time to create a structure that will be interpreted as an array serverside.
// client side ---------------------------------------------
const formData = new FormData();
formData.append('key_name', 'value_1');
formData.append('key_name', 'value_2');
formData.append('key_name', 'value_3');
formData.append('key_name', 'value_4');
const request = new XMLHttpRequest();
request.open("POST", "request_url");
request.send(formData);
// server side ----------------------------------------------
// into the request you find an array if you search into
// POST['key_name'] because the key is repeated and all the
// elements will be grouped into an array
In addition to the method that uses the native object "formdata" it is possible to send complex structures via JSON request as follows.
const sampleArray = [ 'banana', 'orange', 'pear' ];
const sampleJson = {
'other_data_key': 'other_data_value',
'array_of_values': sampleArray
}
const sampleJsonStringified = JSON.stringify(sampleJson);
const request = new XMLHttpRequest();
request.open("POST", "request_url");
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.send(sampleJsonStringified);