Reputation: 1151
I am working on a project with vue.js and to handle my AJAX
requests I use Axios
, I wonder if it is possible to pass as a parameter to a POST
request an array of objects, of this type:
[{id: 1, name: 'max'}, {id: 2, name: 'jhon'}, {id: 3, name: 'anna'}]
If possible, what is the best way to do this?
Upvotes: 6
Views: 19538
Reputation: 216
Lema's answer was the only one that worked for me while using axios + vue + .net Core.
I was trying to send a post to my backend which was expecting an array. Following Lema's implementation I received an string and then deserialized the json string to the type I was expecting.
public IActionResult PostMethod([FromForm]string serialized_object_name){
var expectedArray = JsonConvert.DeserializeObject<ArrayTypeNeeded[]>(serialized_object_name);
}
Upvotes: 1
Reputation: 79
Yes, it's very possible
let data = [
{id: 1, name: 'max'},
{id: 2, name: 'jhon'},
{id: 3, name: 'anna'}
];
let formdata = new FormData();
formdata.append('data',JSON.stringify(data));
axios.post('/url`',formdata)
.then(res => console.log(res))
.catch(err => console.log(err)
On the receiving end (assuming it's PHP & Laravel)
$data = json_decode($request->data);
then loop through $data as it's a normal array
Upvotes: 6
Reputation: 27719
Sure!
let arrOfObj = [
{ name: 'John', lastName: 'Doe' },
{ name: 'Jane', lastName: 'Doe' }
]
axios.post('url_here',arrOfObj)
.then(console.log)
.catch(console.log)
Upvotes: 9