Reputation: 135
I'm trying to add some data to formData like this:
params = {'code': 'h1'}
const formData: FormData = new FormData();
formData.append('parameters', JSON.stringify(params));
When I try to get the data from the formData like this: formData['parameters']
it returns undefined
and formData.entries.length
is 0
.
I looked at some sites and saw that this is the way to do that.
What am I doing wrong?
Thanks.
Upvotes: 10
Views: 15907
Reputation: 21485
You're declaring the formData object incorrectly (edit: for javascript. The question wasn't originally tagged with typescript, which I'm not familiar enough with)
const params={'code': 'h1'}
const formData = new FormData()
formData.append('parameters', JSON.stringify(params))
// confirm:
console.log(formData.get('parameters'))
...but in case you're trying to set multiple parameters on formData, instead of just one named "parameters", you might want to be doing this instead:
const params={
'code': 'h1',
'foo': 'bar'
}
const formData = new FormData()
Object.keys(params).forEach((k) => {
formData.append(k, params[k])
})
// confirm:
console.log(formData.get('code'))
console.log(formData.get('foo'))
Upvotes: 2
Reputation: 20361
Your FormData
object is actually not empty. The way you are trying to access the data after appending it, is wrong.
For me the following works:
const params = {'code': 'h1'}
const formData = new FormData();
formData.append('parameters', JSON.stringify(params));
for (const entry of formData.entries())
{
document.write(entry);
}
Side notes:
formData.entries()
returns an interator object, there is no length
property.[]
defined. So you need to retrieve values using the get() method as shown by Daniel Beck in his answer.Upvotes: 9