Reputation: 207
I need to get the data from a table, allocate it in an array and send it via Json to my Java controller and finally return a Model and View. However, this request can not be ajax due to the return of my controller being a page.
I did it this way as the $ .post documentation:
var orders = new Array();
$("#table-order tbody tr").each(function (){
var col = $(this).children();
if($(this).find('input').is(':checked')) {
var order = {
'number' : $(col[0]).text(),
'desc' : $(col[1]).text(),
'obs' : $(col[2]).text()
};
orders.push(order);
}
});
$.post( "sendToPrint", { array: JSON.stringify(orders) }, function( response ) {
console.log( response );
}, "json");
My Controller:
@RequestMapping(value="/sendToPrint", method = RequestMethod.POST, consumes = "application/json;charset=UTF-8", produces = "application/json;charset=UTF-8")
@Transactional("productTransactionManager")
public ModelAndView imprimir(@RequestBody String ordens) {
ModelAndView mv = new ModelAndView("impressao/impressao");
Gson gson = new Gson();
List<OrdemServico> listaNova = new ArrayList<>();
ArrayList<OrdemServico> listaOrdens = (ArrayList<OrdemServico>) gson.fromJson(ordens, new TypeToken<ArrayList<OrdemServico>>(){}.getType());
for (OrdemServico ordemServico : listaOrdens) {
int mes = LocalDateTime.now().getMonthValue();
int ano = LocalDateTime.now().getYear();
int dia = LocalDateTime.now().getDayOfMonth();
LocalDateTime dataHora = LocalDateTime.of(ano, mes, dia, 0, 0, 0);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String data = dataHora.format(formatter);
ordemServico.setData(data);
listaNova.add(ordemServico);
}
mv.addObject("lista", listaNova);
return mv;
}
The return error:
415 (Unsupported Media Type)
Upvotes: 0
Views: 140
Reputation: 407
Problem occurred because you have specified JSON as the data-type that this controller will consume and you're passing incomplete information in your ajax call. You need to add necessary headers to your ajax call. They are :
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
Upvotes: 0
Reputation: 417
You can post your data with javascript like that;
var xhr = new XMLHttpRequest();
xhr.open("POST", url , TRUE);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({value:value}));
Upvotes: 1