Inicio de sesión

RSS

Distribuir contenido

En línea

En este momento hay 1 usuario y 1 invitado en línea.

Enviar mediante POST y GET usando una sola funcion AJAX

Cuando se realiza una web que usa AJAX, el problema mas frecuente es tener que escribir una funcion para cada variable o conjunto de variables que se quiere pasar. Esto suma mucho peso al código de tu sitio web.

En este tutorial te contamos como crear una sola funcion que te permita pasar variables mediante GET y POST entre dos páginas web usando AJAX .

Esto aligerará mucho el peso de tus archivos javascript y de tus páginas ya que usarás una funcion para todo y no una para cada variable o conjunto de variables que desees pasar.

Antes de empezar

Este tutorial esta hecho para personas que saben cómo crear objetos AJAX, escribir funciones y pasarlas mediante AJAX por POST o GET. Tambien que tienen conocimientos sobre PHP y javascript. Si no es tu caso, por favor profundiza en dichos aspectos a fin de entenderlo.

El código

Primero copio aqui el codigo completo, y luego pasaré a analizarlo.

<script>
function objetus(file) {
xmlhttp=false;
this.AjaxFailedAlert = "Su navegador no soporta las funcionalidades de este sitio y podria experimentarlo de forma diferente a la que fue pensada. Por favor habilite javascript en su navegador para verlo normalmente.\n";
this.requestFile = file;
this.encodeURIString = true;
this.execute = false;
if (window.XMLHttpRequest) {
this.xmlhttp = new XMLHttpRequest();
if (this.xmlhttp.overrideMimeType) {
this.xmlhttp.overrideMimeType('text/xml');
}
}
else if (window.ActiveXObject) { // IE
try {
this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try {
this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
this.xmlhttp = null;
}
}
if (!this.xmlhttp && typeof XMLHttpRequest!='undefined') {
this.xmlhttp = new XMLHttpRequest();
if (!this.xmlhttp){
this.failed = true;
}
}
}
return this.xmlhttp ;
}
function recibeid(_pagina,valorget,valorpost,capa){
ajax=objetus(_pagina);
if(valorpost!=""){
ajax.open("POST", _pagina+"?"+valorget+"&tiempo="+new Date().getTime(),true);
} else {
ajax.open("GET", _pagina+"?"+valorget+"&tiempo="+new Date().getTime(),true);
}
ajax.onreadystatechange=function() {
if (ajax.readyState==1){
document.getElementById(capa).innerHTML = "<img src='loadingcircle.gif' align='center'> Aguarde por favor...";
}
if (ajax.readyState==4) {
if(ajax.status==200)
{document.getElementById(capa).innerHTML = ajax.responseText;}
else if(ajax.status==404)
{
capa.innerHTML = "La direccion no existe";
}
else
{
capa.innerHTML = "Error: ".ajax.status;
}
}
}
if(valorpost!=""){
ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
ajax.send(valorpost);
} else {
ajax.send(null);
}
}
</script>
Autor

Enviar un comentario nuevo

El contenido de este campo se mantiene como privado y no se muestra públicamente.
  • Las direcciones de las páginas web y las de correo se convierten en enlaces automáticamente.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <i> <b> <h2> <h3> <tt> <blockcode>
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.
  • Saltos automáticos de líneas y de párrafos.
  • Every instance heading tags will be modified to include an id attribute for anchor linking.
  • Se pueden agregar imágenes a este envío.
  • Every instance of "<!--tableofcontents-->" in the input text will be replaced with a collapsible mediawiki-style table of contents. Accepts options for title, list style, minimum heading level, and maximum heading level as follows: <!--tableofcontents list: ol; title: Table of Contents; minlevel: 1; maxlevel: 3;-->. All arguments are optional and defaults are shown.

Más información sobre opciones de formato


Publicidad