I'm new at AJAX , and i'm strugglying to pass an object to a controller.
i tried this :
$(document).ready(function(){
$('#mov').click(function(){
var dni = parseInt($('#dni').val());
var table = $('#tablaSeleccionados').tableToJSON();
$.ajax({
type:'POST',
url:'${pageContext.request.contextPath}/saveMovBienes',
data: {dni:dni,table:table},
dataType: "json"
})
})
})
Controller
@PostMapping("/saveMovBienes")
public String saveMovBienes(@RequestParam(name="dni", required=false) Integer dni,
@RequestParam(name="table", required=false) String listado) {
System.out.println("PER_ID= " dni);
System.out.println("LIST= " listado);
return "";
}
Tried changing the format of "listado" to List , Json, String, and nothing ...
If i add "toString()" to my var table, i see the elements in the controller, but like this: 'object [Object]', 'object [Object]'
Any guidence will be thankful.
CodePudding user response:
You may want to send your data as JSON in the body of the request, since you are creating a POST
request:
$.ajax({
type: 'POST',
url: ...,
data: JSON.stringify({ dni: dni, table: table }),
dataType: "json",
contentType: 'application/json; charset=utf-8',
})
On the backend you can hava a @RestController
which will receive the data in a data transfer object (DTO) annotated with @RequestBody
.
First, you have to create a DTO for the request body:
public class MyRequest {
private String dni;
private String table;
// Getters and setters
}
Now, you cam create the rest controller:
@RestController
public class MyController {
@PostMapping("/saveMovBienes")
public String saveMovBienes(@RequestBody MyRequest request) {
System.out.println("PER_ID= " request.getDni());
...
}
}