Ejemplos de AJAX

Ejemplo 1 (Básico)


demo1.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>demo AJAX 1</title>
    <script type="text/javascript" language="javascript">
      function makeRequest(url) {
      var http_request = false;
      if (window.XMLHttpRequest) {
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
          http_request.overrideMimeType('text/xml');
        }
      } else if (window.ActiveXObject) {
        try {
          http_request=new ActiveXObject("Msxml2.XMLHTT");
        } catch(e) {
          try {
            http_request = new ActiveXObject("Microsoft.XMLHTTP");
          } catch(e) {}
        }
      }
      if (!http_request) {
        alert("No se pudo crear XMLHTTP");
        return false;
      }
      http_request.onreadystatechange = function() {alertContent(http_request);};
      http_request.open('GET',url,true);
      http_request.send(null);
      }
 
      function alertContent(http_request) {
        if (http_request.readyState == 4) {
          if (http_request.status == 200) {
            alert('Rotorno: '+http_request.responseText);
          } else {
            alert("Problemas en la comunicación");
          }
        }
      }
    </script>
  </head>
 
  <body>
    <h1>demo AJAX 1</h1>
 
    <span style="cursor:pointer; text-decoration:underline"
      onclick="makeRequest('demo.txt')">demo
    </span>
    <br>
    Demo <a href="javascript:makeRequest('demo.txt')">aqui</a><br>
    Demo <a href="javascript:alert('demo.txt')">aqui</a><br>
    <form action="" name="forma">
      <textarea id="res" name="res" rows="4" cols="40">
      </textarea>
    </form>
    <hr>
  </body>
</html>

demo.txt

Este es el contenido del archivo demo.txt

Ejemplo 2 (CGI+XML)


demo2.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>demo AJAX 2</title>
    <script type="text/javascript" language="javascript">
      function makeRequest(url) {
      var http_request = false;
      if (window.XMLHttpRequest) {
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
          http_request.overrideMimeType('text/xml');
        }
      } else if (window.ActiveXObject) {
        try {
          http_request=new ActiveXObject("Msxml2.XMLHTT");
        } catch(e) {
          try {
            http_request = new ActiveXObject("Microsoft.XMLHTTP");
          } catch(e) {}
        }
      }
      if (!http_request) {
        alert("No se pudo crear XMLHTTP");
        return false;
      }
      http_request.onreadystatechange = function() {alertContent(http_request);};
      http_request.open('GET',url,true);
      http_request.send(null);
      }
 
      function alertContent(http_request) {
        if (http_request.readyState == 4) {
          if (http_request.status == 200) {
            var xmldoc = http_request.responseXML;
            var demo_node = xmldoc.getElementsByTagName('demo').item(0);
            document.getElementById('res').value=http_request.responseText;
            alert(demo_node.firstChild.data);
          } else {
            alert("Problemas en la comunicación");
          }
        }
      }
    </script>
  </head>
  <body>
    <h1>demo AJAX 2</h1>
 
    <span style="cursor:pointer; text-decoration:underline"
      onclick="makeRequest('demo.py?a=demo')">demo
    </span>
    <br>
    Demo <a href="javascript:makeRequest('demo.py?a=3')">aqui</a><br>
    <form action="" name="forma">
      <textarea id="res" name="res" rows="4" cols="40">
      </textarea>
    </form>
    <hr>
    <div id="res"></div>
    <hr>
  </body>
</html>

demo.py

#!/usr/bin/python
import cgi
 
datos = cgi.FieldStorage()
 
print "Content-type: text/xml"
print "Cache-control: no-cache\n"
 
print "<?xml version='1.0' ?>"
print "<demo>Demo desde python <dato>%s</dato></demo>" % datos['a'].value

Ejemplo 3 (Slides)


demo3.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>demo AJAX 3</title>
    <script type="text/javascript" language="javascript">
      function makeRequest(url) {
      var http_request = false;
      if (window.XMLHttpRequest) {
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
          http_request.overrideMimeType('text/xml');
        }
      } else if (window.ActiveXObject) {
        try {
          http_request=new ActiveXObject("Msxml2.XMLHTT");
        } catch(e) {
          try {
            http_request = new ActiveXObject("Microsoft.XMLHTTP");
          } catch(e) {}
        }
      }
      if (!http_request) {
        alert("No se pudo crear XMLHTTP");
        return false;
      }
      http_request.onreadystatechange = function() {alertContent(http_request);};
      http_request.open('GET',url,true);
      http_request.send(null);
      }
 
      function alertContent(http_request) {
        if (http_request.readyState == 4) {
          if (http_request.status == 200) {
            document.getElementById('res').innerHTML=http_request.responseText;
          } else {
            alert("Problemas en la comunicación");
          }
        }
      }
    </script>
  </head>
 
  <body>
    <h1>demo AJAX 3</h1>
 
    <span style="cursor:pointer; text-decoration:underline"
      onclick="makeRequest('slide.py?titulo=Demo de Slide')">demo
    </span>
    <br>
    Demo <a href="javascript:makeRequest('slide.py?titulo=Otro slide más')">aqui</a><br>
    Inicio <a href="javascript:makeRequest('slide.py?id=1')">aqui</a><br>
    <hr>
    <div align="center" id="res"></div>
    <hr>
  </body>
</html>

demo.py

#!/usr/bin/python
import cgi
 
datos = cgi.FieldStorage()
 
print "Content-type: text/xml"
print "Cache-control: no-cache\n"
print "<?xml version='1.0' ?>"
 
print "<table width='300' height='200' bgcolor='yellow'>"
if datos.has_key('id'):
        id = int(datos['id'].value)
        if id>0:
                print """<div align='left' onclick="makeRequest('slide.py?id=%s')">"""%(id+1)
                print "<h3>Primer Slide</h3>"
                print "<ul>"
                print "<li>Priemera linea</li>"
        if id>1:
                print "<li>Segunda linea</li>"
        if id>2:
                print "<li>Linea final</li>"
        if id>0:
                print "</ul></div>"
else:
        print   "<h3>%s</h3>"%datos['titulo'].value
        print "<hr/><p>Datos del slide</p>"

Ejemplo 4 (Submit)


demo4.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Demo DOM con tablas</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <script type="text/javascript" language="javascript">
      function makeRequest(url,par) {
      var http_request = false;
      if (window.XMLHttpRequest) {
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
          http_request.overrideMimeType('text/xml');
        }
      } else if (window.ActiveXObject) {
        try {
          http_request=new ActiveXObject("Msxml2.XMLHTT");
        } catch(e) {
          try {
            http_request = new ActiveXObject("Microsoft.XMLHTTP");
          } catch(e) {}
        }
      }
      if (!http_request) {
        alert("No se pudo crear XMLHTTP");
        return false;
      }
      http_request.onreadystatechange = function() {resContent(http_request);};
      http_request.open('POST',url,true);
      http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      var f = document.getElementById("forma")
      var dat = f.elements;
      par = par+'a1='+dat['a1'].value+';b1='+dat['b1'].value
      http_request.setRequestHeader("Content-length", par.lenght);
      http_request.setRequestHeader("Connection", "close");
 
      http_request.send(par);
      }
 
      function resContent(http_request) {
        if (http_request.readyState == 4) {
          if (http_request.status == 200) {
            document.getElementById('res').innerHTML=http_request.responseText;
            var xmldoc = http_request.responseXML;
            var d1 = xmldoc.getElementsByTagName('valor').item(0);
            var d2 = xmldoc.getElementsByTagName('valor').item(1);
            fres = document.getElementById('fres')
            fres.elements['r1'].value = d1.textContent
            fres.elements['r2'].value = d2.textContent
         } else {
                      alert("Problemas en la comm");
          }
        }
      }
    </script>
 
<script>
   var cont=1;
	function addrow(tc1,tc2) {
		var tbl = document.getElementById('tabla');
		var row = document.createElement('tr');
		var c0 = document.createElement('td')
      c0.innerHTML=cont;
		var c1 = document.createElement('td')
		var d1 = document.createElement('input')
		d1.setAttribute('name','a'+cont)
		d1.setAttribute('value',tc1)
		c1.appendChild(d1)
      //c1.innerHTML=tc1;		
		var c2 = document.createElement('td')
		var d2 = document.createElement('input')
		d2.setAttribute('name','b'+cont)
		d2.setAttribute('value',tc2)
		c2.appendChild(d2)
      //c2.innerHTML=tc2;		
		row.appendChild(c0);
		row.appendChild(c1);
		row.appendChild(c2);
		tbl.appendChild(row);
      cont++;		
	}
 
	function addrow2() {
	   var frm = document.getElementById('forma');
	   addrow(frm.c1.value,frm.c2.value);
	}
</script>
</head>
<body>
<h2>Demo de DOM con tablas</h2>
<form id='forma' action="demo2.py">
 
Columna 1:<input type="text" name="c1"> 
Columna 2:<input type="text" name="c2">
<input type="button" value="add"  onclick="javascript:addrow2()">
<input type="reset">
<input type="submit">
<input type="button" value="submit ajax"  onclick="javascript:makeRequest('demo2.py','')">
<div onclick="javascript:addrow('vacio','vacio')">Adicionar fila</div><br/>
<table cellpadding="0" cellspacing="0" border="1"  id="tabla">
<tr>
<td></td><th>col 1</th><th>col 2</th>
</tr>
</table>
 
</form>
<hr>
<div align="center" id="res"></div>
<form id="fres">
<input name='r1'><input name='r2'>
</form> 
</body>
</html>

demo2.py

#!/usr/bin/python 
import cgi
 
datos = cgi.FieldStorage()
 
print "Content-type: text/xml"
print "Cache-control: no-cache\n"
 
print "<?xml version='1.0' ?>"
print "<datos>"
for k in datos.keys():
    print "<llave>%s</llave><valor>%s</valor>" % (k,datos[k].value)
print "</datos>"
 
materias/laboratorio_de_lenguajes_ii/lableng2/ejemplosajax.txt · Última modificación: 2011/01/24 15:30 (editor externo)
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki