Foros del Web » Programando para Internet » Javascript » Frameworks JS »

Problema con AJAX jsp Serlvets POST

Estas en el tema de Problema con AJAX jsp Serlvets POST en el foro de Frameworks JS en Foros del Web. Hola a todos. Me encuentro renegando con AJAX para hacer un alta en una BD mysql por metodo post. La primera vez que llamo a ...
  #1 (permalink)  
Antiguo 13/07/2011, 13:45
Avatar de javi10823  
Fecha de Ingreso: agosto-2008
Ubicación: Madrid, Spain, Spain
Mensajes: 17
Antigüedad: 15 años, 8 meses
Puntos: 2
Problema con AJAX jsp Serlvets POST

Hola a todos. Me encuentro renegando con AJAX para hacer un alta en una BD mysql por metodo post.
La primera vez que llamo a la función anda perfecto. Cuando intento agregar el 2do elemento , en la bd lo inserta perfecto , pero no me actualiza el contenido del listado de localdades nuevas , mientras que en primera instancia lo hace perfecto. Alguien sabe que estoy haciendo mal?

Copio el codigo de la jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="com.presentacion.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script src="./jquery/jquery-1.6.2.min.js" type="text/javascript"></script>
<script language="javascript">
var ajax;

function getXMLObject() //XML OBJECT
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}


function alta()
{



ajax = new getXMLObject(); //xmlhttp holds the ajax object

var localidad = document.getElementById("localidadid").value;

var params="localidad="+localidad;



// Enviamos la peticion

ajax.open( "POST", "Servlet_Alta_Localidad"+"?"+params, true );
ajax.onreadystatechange = funcionCallback;
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajax.send( params );


}



function EliminarLocalidad(id)
{

document.getElementById("cargando").style.display = 'block';

//alert("elimina");

ajax = new getXMLObject(); //xmlhttp holds the ajax object


// Enviamos la peticion

ajax.open( "POST", "Servlet_Eliminar?id="+id, true );
ajax.send( "" );

delay2();




}

function delay(){

setTimeout('eval(RecuperarLocalidades);',1500);



}


function delay2(){

setTimeout('RecuperarLocalidades();',100);



}





function funcionCallback()
{

//alert("callback");

// Comprobamos si la peticion se ha completado (estado 4)
if( ajax.readyState == 4 )
{
// Comprobamos si la respuesta ha sido correcta (resultado HTTP 200)
if( ajax.status == 200 )
{
// Escribimos el resultado en la pagina HTML mediante DHTML
document.getElementById("localidades").innerHTML = "<b>"+ajax.responseText+"</b>";

}
}
}

function RecuperarLocalidades()
{

//alert("cargarlocalidades");

ajax = new getXMLObject(); //xmlhttp holds the ajax object

// Almacenamos en el control a la funcion que se invocara cuando la peticion
// cambie de estado
ajax.onreadystatechange = funcionCallback;

// Enviamos la peticion
ajax.open( "GET", "Servlet_Listar_Localidades", true );
ajax.send( "" );

document.getElementById("cargando").style.display = 'none';



}

$(document).ready(function() {
// initialization code goes here
RecuperarLocalidades();
});


</script>
<script type="text/javascript">
function validar(e) {
tecla = (document.all) ? e.keyCode : e.which;
if (tecla==13)

// alert ('Has pulsado enter');
alta();
}
</script>
</head>

<body >

<h1>Alta Localidad</h1>
<%

response.setHeader("Cache-Control","no-store"); //HTTP 1.1
response.setHeader("Pragma","no-cache"); //HTTP 1.0
response.setDateHeader("Expires", 0); // prevents caching at the proxy server

Procesador proc = new Procesador();

String errores = (String) request.getSession().getAttribute("error");

if (errores==null)
{
errores="";
}


%>
<form name="formulario">
<label for"localidadid">Localidad</label>&nbsp;
<input type="text" onkeypress="validar(event)" name="localidad" id="localidadid" style=" width : 337px;"/>
<br/><br/>
</form>
<input type="button" onclick="alta()" value="Alta Localidad" />
<br/><br/>
<%=errores%>
<br/><br/>
<div id="cargando" style="display: none;">
<label for="carga">Loading</label>&nbsp;<img src="./img/cargando.gif" id="carga">

</div>
<br/><br/>

<h3>Listado de Localidades</h3>

<br/>
<div id="localidades">


</div>
<%

errores=null;
request.getSession().removeAttribute("error");

%>
</body>
</html>



y copio el codigo del servlet de alta:


package com.presentacion;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Servlet implementation class Servlet_Alta_Localidad
*/
public class Servlet_Alta_Localidad extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public Servlet_Alta_Localidad() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub

}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub


try {

String localidad = request.getParameter("localidad");

EntityManager EM = new EntityManager();

if (EM.AltaLocalidad(localidad) == false)

{
request.getSession().setAttribute("error", EM.getErrores());

}


} catch (Exception e) {
// TODO: handle exception
response.sendRedirect("index.jsp");
System.out.println(e);
}

}

}

GRACIAS POR ADELANTADO
SALUDOS

Etiquetas: ajax, contenido, jsp, post, formulario
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 09:19.