Created
March 14, 2014 08:52
-
-
Save tanrax/9544289 to your computer and use it in GitHub Desktop.
AJAX: Envío de datos (Enviar por GET)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html lang="es"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Ejemplo de formulario con AJAX</title> | |
<style> | |
body { | |
font-size: 14px; | |
text-align: center; | |
} | |
input, textarea { | |
display: block; | |
margin: 0 auto; | |
margin-top: 1.2em; | |
padding: 0.5em; | |
font-size: 1em; | |
} | |
</style> | |
</head> | |
<body> | |
<h1>Envíame tu mensaje</h1> | |
<input type="text" id="nombre" placeholder="Tu nombre"> | |
<input type="text" id="asunto" placeholder="El asunto"> | |
<input type="email" id="correo" placeholder="Tu e-mail"> | |
<textarea name="mensaje" id="mensaje" cols="30" rows="10"></textarea> | |
<input type="button" onclick="enviar()" value="contactar"> | |
<p id="respuesta"></p> | |
<script> | |
/** | |
* Método que envia los datos por AJAX | |
*/ | |
function enviar() { | |
oXML = AJAXCrearObjeto() | |
oXML.onreadystatechange = procesaRespuesta | |
oXML.open("GET", "procesar.php?" + crearCadenaGET(), true) | |
oXML.send(''); | |
} | |
/** | |
* Método que forma la cadena GET | |
* @return String sTotal | |
*/ | |
function crearCadenaGET() { | |
var sNom = encodeURIComponent(document.getElementById('nombre').value) | |
var sAsunto = encodeURIComponent(document.getElementById('asunto').value) | |
var sCorreo = encodeURIComponent(document.getElementById('correo').value) | |
var sMens = encodeURIComponent(document.getElementById('mensaje').value) | |
var sTotal = 'nombre=' + sNom + '&asunto=' + sAsunto | |
+ '&correo=' + sCorreo + '&mensaje=' + sMens + '&nocache=' | |
+ Math.random() | |
return sTotal | |
} | |
/** | |
* Método que crea el objeto XMLHttp (AJAX) | |
*/ | |
function AJAXCrearObjeto() { | |
if(window.XMLHttpRequest) { | |
return new XMLHttpRequest() | |
} else if(window.ActiveXObject) { | |
return new ActiveXObject("Microsoft.XMLHTTP") | |
} | |
} | |
/** | |
* Método que espera a que la informacion se reciba, después | |
* lo imprime en el HTML | |
*/ | |
function procesaRespuesta() { | |
if(oXML.readyState == 4) { | |
document.getElementById("respuesta").innerHTML = oXML.responseText | |
} | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment