ebyte
ebyte

Reputation: 1517

vue axios post how to submit formdata array?

I need to submit an ARRAY data because the backend can only recognize such data

Expected effect:

&row[weigh]=0
&row[status]=normal

code:

row:{
  weigh: 0,
  status: 'normal'
}

actual effect:

row:{
  weigh: 0,
  status: 'normal'
}

When I submit the data, the console displays JSON instead of Array, but the backend cannot get it

What I need is to be consistent with the results from the form submission below

<form  method="POST" >
  <input name="row[a]" type="text" value="">
  <input name="row[b]" type="text" value="">

Upvotes: 1

Views: 2418

Answers (4)

Vijay Joshi
Vijay Joshi

Reputation: 959

Try this code.

let row = {
  weigh: 0,
  status: 'normal'
};

let finalArr = [];

Object.keys(row).forEach((key) => {
    finalArr.push(`row[${key}]=` + row[key]);
});
console.log(finalArr.join('&'));
// outputs: row[weigh]=0&row[status]=normal

Upvotes: 0

ebyte
ebyte

Reputation: 1517

ok

const formData = new FormData()
  Object.keys(this.form).forEach(e => {
  formData.append(`row[${e}]`, this.form[e])
})

Upvotes: 0

Qonvex620
Qonvex620

Reputation: 3972

Your code also should pass an array just like this.

data = [
  {weigh: 0},
  {status: 'normal'}
]

then when you send it to server for example using axios, your code should look like this

axios.post('/api endpoint', {row:data})
    .then(response => {
     // response here
});

Upvotes: 0

Tony Tom
Tony Tom

Reputation: 1583

public register(rowObject: RowObject): AxiosPromise<any> {
    return axios.post('http://localhost/api/register', rowObject);
}

This way you can pass the data in Post method.

rowObject =  {
    weigh: 0,
    status: 'normal'
    }

Upvotes: 1

Related Questions