4

I observed the setting the JSON data in HTML5DND will be converted into string. Are there any alternatives and best practices for passing JSON Data other than stringifying.

// During drag enter
event.dataTransfer.setData('application/json', {
  id: 1
});


// During Drop data is printing as object
let data = event.dataTransfer.getData('application/json');
// printing [object Object]
vishnu sandhireddy
  • 1,148
  • 1
  • 7
  • 12

2 Answers2

2

There is no alternative for DataTransfer.setData() because its data (second) argument is a DOMString.

There is an alternative to DataTransfer--DataTransferItem; however, using it will involve stringifying the object (to pack that into a Blob of mimetype JSON).

greg-tumolo
  • 698
  • 1
  • 7
  • 30
0

In case my other answer does not answer your question, try dragging/dropping the object avatars into the textarea.

const object_1 = {id: 1}
const object_2 = {id: 2}
const p_1 = document.body.appendChild(document.createElement("p"))
const p_2 = document.body.appendChild(document.createElement("p"))
p_1.innerText = "object_1"
p_1.draggable = true
p_2.innerText = "object_2"
p_2.draggable = true
p_1.ondragstart = function () {
    event.dataTransfer.setData("text", "object_1")
}
p_2.ondragstart = function () {
    event.dataTransfer.setData("text", "object_2")
}
const textarea = document.body.appendChild(document.createElement("textarea"))
textarea.ondrop = function() {
    event.preventDefault()
    this.innerText = eval(event.dataTransfer.getData("text")).id
}
greg-tumolo
  • 698
  • 1
  • 7
  • 30