I must create a POST with AJAX request in JQuery, where I must pass an array of objects that I can create with:
var actor=new Array();
for(var i=1;i<=incr;i++)
{
actor.push({"name": document.getElementById("idAN"+i).value,
"surname": document.getElementById("idAS"+i).value,
"dateborn": document.getElementById("idAB"+i).value,
"gender": document.getElementById("idAG"+i).value,
"movie": datas});
alert("actorX: "+actor[i-1].surname);
}
$.ajax({
method:'POST',
dataType: 'json',
data:{ actors: actor },
url:'http://localhost:8080/movies/actors',
success: function (rest) {
alert("aggiunto attore");
},
error: function(rest){
alert("non aggiunto attore");
}
});
I receive the data with this Java method, but this doesn't work. anyone can help me?
@RequestMapping(value = "movies/actors", method = RequestMethod.POST)
public ArrayList<Actor> addActors(@RequestBody Actor[] actors) {...}
After three days of work, i solve this with the help from the comments. This is the result of the method in java:
@CrossOrigin(origins = "http://localhost:8080")
@RequestMapping(value = "movies/actors", method = RequestMethod.POST,headers="Accept=application/json")
public @ResponseBody ArrayList<Actor> add (@RequestBody Actor[] actors) {
//Actor[] actors = actobj.getAllActors();
ArrayList<Actor> json = new ArrayList<Actor>();
for(Actor A : actors){
System.out.println("Arrivo");
serv.addActor(new Actor(A.getName(),A.getSurname(),A.getBorn(),A.getGender(),A.getMovie()));
System.out.println("nomeAttore"+A.getName());
json.add(A);
}
return json;
}
and this is the post request:
$.ajax({
method:'POST',
dataType: 'json',
data:JSON.stringify(actor),
contentType: "application/json; charset=utf-8",
url:'http://localhost:8080/movies/actors',
success: function (rest) {
alert("aggiunto attore");
},
error: function(rest){
alert("non aggiunto attore");
}
});
In particular, i changed a value of a parameter in the query sql from databorn to born, because i have the method getBorn and setBorn, the name must be eguals; and eguals must be the name of the object's parameter in the array actor in javascript: born