It tells me that it's undefined the name of the variable that I'm asking Jquery, but I put console.log (data) and it returns the complete array and with its variables
$(function () {
array_producto = [];
$.ajax({
url: "ofertas_guardadas",
dataType: 'json',
contentType: "application/json",
error: function () {
alert("Error");
},
success: function (data) {
console.log(data);
$.each(data, function (i, item)
{
var json = item.nombre;
alert(json);
});
}
});
servlet
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/plain");
HttpSession sesion = request.getSession(false);
PrintWriter out = response.getWriter();
int id_consumidor = Integer.parseInt(sesion.getAttribute("id_consumidor").toString());
String producto;
String nombre, precio_oferta, precio_normal, id, ruta;
JSONArray lista = new JSONArray();
productoFacade.oferta_guardadas(id_consumidor);
for (Producto p : productoFacade.oferta_guardadas(id_consumidor)) {
nombre = p.getNombreProducto();
id = p.getIdProducto().toString();
precio_normal = p.getPrecioNormal().toString();
precio_oferta = p.getPrecioOferta().toString();
ruta = p.getRutaImagen();
producto = new StringBuilder("{").
append("\"nombre\":\"" + nombre + "\",").
append("\"id\":\"" + id + "\",").
append("\"precio_normal\":\"" + precio_normal + "\",").
append("\"precio_oferta\":\"" + precio_oferta + "\",").
append("\"ruta\":\"" + ruta + "\"").
append("}").toString();
lista.put(producto);
}
out.print(lista.toString());
}
I also tried this
success: function (data) {
console.log(data);
$.each(data, function (i, item)
{
console.log(data[i].nombre)
var json = JSON.parse(data[i].nombre);
alert(json);
});