简体   繁体   中英

Storing an array of strings in hidden elements on an HTML page in JavaScript

On a web application I am developing, I have table where the user can select multiple rows, and the page can then send the IDs of the selected rows to the back-end controller in an AJAX request using JavaScript.

The way this is currently done is that the JavaScript code writes these IDs as a comma-separated list in the value of a hidden HTML element, and then send the entire list in the AJAX request. This works, but the back-end controller has to parse the list back into individual values to be able to use them, and I'm not sure how this would work if the IDs can actually contain commas.

I'd like to handle the IDs as an array all the way through, but I don't know what would be the best way to store them in hidden elements. Is it possible to have several elements with the same "id" or "name" attribute and then read all their values into an array, or would some other attribute work better? Or is having separate elements for each value a good idea in the first place?

You could store them in hidden elements already prepared to be plucked out and sent to your backend, by calling JSON.stringify on the array before inserting it into the hidden element.

What would probably be less painful in the long run, though, would be holding onto that data in an object and using something else on the DOM (such as an element ID, the innerText of some element, a data-whatever attribute, etc.) as the key. This would also get rid of the need to write and retrieve data from the DOM.

<td data-something="foo"></td>
const rowsToIdsMap = { 'foo': ['a', 'b', 'c'] }

// attach with an onclick attribute, in JS, or whatever
function someClickHandler (evt) {
  const ids = rowsToIdsMap[evt.target.getAttribute('data-something')]
  // handle the rest of your ajax call
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM