Home > Mobile >  vue - cannot convert submitEvent.target to formdata
vue - cannot convert submitEvent.target to formdata

Time:10-03

update

I made a correct function based on the answer below

export function submitEvent_2_json(e) {
    const jsondata = {}
    let fd= new FormData(e.target)
    for (let key of fd.entries()) {
        jsondata[key[0]]=key[1]
    }
    return jsondata
}

origional problem

I'm trying to get data from form and convert it to json
It's obvious that data is in submitEvent.target(as follow picture), but the result is undefined or null

<template>
<form @submit.prevent="submit">
  <input id="aa"/>
  <button type="submit">ok</button>
</form>
</template>

<script setup>
function submit(e) {
  console.log(e)
  let fd= new FormData(e.target)
  console.log(fd)
  console.log(e.formData)
  console.log(fd.entries())
}
</script>

output
submitevent output

CodePudding user response:

That's how FormData works

FormData is a special type of object which is not stringifyable can cannot just be printed out using console.log

If you want to get an item inside, you can use get method.

EX:

fd.get('username');

If you want get all entries inside, you can loop through

for (var key of fd.entries()) {
  console.log(key[0]   ', '   key[1])
}
  • Related