I'm having a hard time trying to get the date in Ajax.
When I run the code, I get the 200 status and in network in the Chrome debugger I can see the return, but I can not do anything else with the date, like giving an alert or anything useful.
Can anyone help me?
JS - Ajax
<script>
$(document).ready(function () {
$('#calcular').on('click', function () {
var nome = $('#nome').val();
var peso = $('#peso').val();
var altura = $('#altura').val();
$.ajax({
url: 'calcular',
method: 'get',
dataType: 'json',
data: {
nome: nome,
peso: peso,
altura: altura
},
success: function (data, textStatus, jqXHR) {
alert(data);
},
statusCode: {
400: function() {
alert("Chamada inválida!");
}
}
});
});
});
</script>
Servlet
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
String nome = request.getParameter("nome");
double peso = Double.parseDouble(request.getParameter("peso"));
double altura = Double.parseDouble(request.getParameter("altura"));
IMC imc = new IMC(nome, peso, altura);
String user = imc.getNome();
double resultado = imc.getIMC();
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.printf(Locale.US, "{ \"user\": %s, \"resultado\": %.2f }", user, resultado);
} catch (NumberFormatException ex) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
}
}
}
IMC Class
package models;
public class IMC {
private String nome;
private double peso, altura;
public IMC (String nome, double peso, double altura){
this.nome = nome;
this.peso = peso;
this.altura = altura;
}
public String getNome() {
return nome;
}
public double getIMC () {
return peso / (altura * altura);
}
}