Anda di halaman 1dari 17

1.

EJEMPLO DE ACCESO A ARCHIVOS XML DESDE JAVASCRIPT


DE: http://metafisicainformatica.blogspot.com.ar/2009/07/integrar-javascript-y-xml- nejemplo.html Vamos a mostrar, a travs de un ejemplo, la sencilla manera en la que podemos integrar JavaScript y XML. Supongamos que queremos incluir en nuestra web un apartado que contenga una lista de iperv!nculos "o lin#s$. %l problema es que esta lista va a variar continuamente y no queremos andar modi&icando el '(ML cada ve). La solucin consiste en tener la lista de iperv!nculos en un arc ivo XML e*terno y cargar la lista din+micamente ayudados de JavaScript y su parser XML. ,uestro arc ivo XML tiene el siguiente &ormato-

<?xml <lista>

version="1.0"

encoding="iso-8859-1"?>

<link> <titulo>Google< titulo> <!re">!tt#$ %%%.google.es< !re"> < link> <link> <titulo>&eta"'sica de (ostum)res< titulo> <!re">!tt#$ meta"isicadecostum)res.)logs#ot.com< !re "> < link> <link> <titulo>&eta"'sica *n"orm+tica< titulo> <!re">!tt#$ meta"isicain"ormatica.)logs#ot.com< !re" > < link> < lista>

.n detalle importante es la cabecera XML. Necesita os es!eci"ica# enco$in%&'iso())*+(1' !a#a e,ita# !#o-le as con las til$es . las / . /e no acerlo, nos aparecer!an s!mbolos raros en lugar de 0 y vocales acentuadas.

%l c1digo JavaScript que necesitamos para resolver nuestro problema es el siguiente-

<!tml> <)od,> <div id="links">< div> <scri#t t,#e="text -avascri#t"> .n la varia)le div/links o)tenemos el contenedor div con el id 0links0 var div/links = document.get.lement1,*d20links034 var i" 9 xml5oc = 2xml5oc cargar6&75oc20links.xml034 8= null3

:)tenemos la lista de links var links/tag = xml5oc.get.lements1,;ag<ame2"lista"3 =0>.get.lements1,;ag<ame2"link"34 "or 2var i = 04 i < links/tag.lengt!4 i??3 9 link =

:)tenemos el t'tulo del var titulo links/tag=i>.get.lements1,;ag<ame2"titulo"3 =0>.c!ild<odes=0>.node@alue4

:)tenemos el !i#erv'nculo del link var !re" = links/tag=i>.get.lements1,;ag<ame2"!re""3 =0>.c!ild<odes=0>.node@alue4 &odi"icamos el contenido !tml del contenedor div div/links.innerA;&7 ?= "<#><a !re"=" ? !re" ? ">" ? titulo ? "< a>< #>"4 B B "unction 9 i" cargar6&75oc2arc!ivo6&73 var xml5oc4

else

2%indo%.6&7Att#CeDuest3 9 xml5oc = ne% %indo%.6&7Att#CeDuest234 xml5oc.o#en2"G.;"E arc!ivo6&7E "alse34 xml5oc.send2""34 return xml5oc.res#onse6&74 B #ara *. 5 , *. F i" 2Gctive6:)-ect2"&icroso"t.6&75:&"33

9 xml5oc = ne% Gctive6:)-ect2"&icroso"t.6&75:&"34 xml5oc.as,nc = "alse4 xml5oc.load2arc!ivo6&734 return xml5oc4 B alert2".rror cargando el documento."34 return null4 B < scri#t> < )od,> < !tml>

2uedes encontrar in&ormaci1n detallada sobre el parser XML "en ingls$ aqu!.

2. !omo leer xml con javascript


DE: http://social.ms"n.microsoft.com/#or ms/es-E$/0%0c7f0f-9&%c-%c0e-'()7(eaf"f*'*c0e/como-leer-xml-con-javascript+for m,netfx-ebes
#oros "e Desarrollo . /$0.1E2 Pregunta

0
3nicie sesi4n para votar

2engo n javascript el c al lee los sig ientes elementos 567

<?xml version=").0" enco"ing,"82#-'"+. <eventos> <evento> <"ec!a>01 0H I01I9/fecha. <!ora>I0$009/hora. <comentario>(ine9/comentario. < evento> <evento> <"ec!a>01 1J I01I9/fecha. <!ora>08$009/hora. <comentario>(arrera &atutina9/comentario. < evento> < eventos>
Es el sig iente

"unction G)rirKic!ero2"ic!6&73 9 var xml5oc = unde"ined4 try 9 if 2document.all3 //3E 9 xml5oc = ne- Gctive6:)-ect2:6icrosoft.567D;6:34 B

else //firefox 9 xml5oc = document.im#lementation.create5ocument2::E ::E n ll34 B xml5oc.as,nc = false4 xml5oc.load2"ic!6&734 B catch 2e3 9 try 9 //otros safari< chrome var xml!tt# = ne- %indo%.6&7Att#CeDuest234 xml!tt#.o#en2:=E2:E "ic!6&7E false34 xml!tt#.send2n ll34 xml5oc = xml!tt#.res#onse6&7.document.lement4 ret rn xml5oc4 B catch 2e3 9 ret rn unde"ined4 B B ret rn xml5oc4 B"unction (argar6&7.ventos23 9 try 9 xml5oc = G)rirKic!ero2:/calen"ario.xml:34 eventos6&7 = xml5oc.get.lements1,;ag<ame2>evento>34 if 2eventos6&7.lengt! > 03 9 eventos = ne- Grra,234 //clase con los "atos carga"os B for 2var i = 04 i < eventos6&7.lengt!4 i??3 9 GDu' o)tengo el valor #or el nom)re de la etiDueta xml.vento = eventos6&7=i>4 "ec!a = Get@alue2:fecha:34 !ora = Get@alue2:hora:34 comentario = Get@alue2:comentario:34 B ret rn eventos4 B catch 2e3 9 alert2:$e pro" jo n error en la carga "e los "atos:34 B B"unction Get@alue2atri)uto3 9 var valor = xml.vento.get.lements1,;ag<ame2atri)uto34 if 2valor=0> 8= n ll LL valor=0> 8= unde"ined3 ret rn valor=0>."irst(!ild.node@alue4 else ret rn n ll4 B

0. XML 1 Inte%#acin Ja,aSc#i!t DE: http://blog.t tiempo.net/xml-integracion-javascript/


2ublicado el 34 de enero de 3567 por (utiempo.net

Comenzamos los ejemplos de integracin de nuestros datos XML para vuestras pginas con un sencillo cdigo JavaScript.

Para el ejemplo no se han utilizado todos los datos, pero es una manera sencilla de comenzar. ueda de tu parte dar estilo, colores ! "ormato al resultado "inal #ue #uieras conseguir para tu $e%.

Cdigo JavaScript:
) 2 (
B <scri#t t,#e="text -avascri#t"> "unction is<um)er2n3 9 return 8is<a<2#arseKloat2n33 LL isKinite2n34

% * & 7 ' 9 ) 0 ) ) ) 2 ) ( ) % ) * ) & ) 7 ) '


i" 2xml5oc 8= null3 9 var *m#rimirAorasAtml = 0<ta)le cell#adding="0" cells#acing="0" st,le="%idt!$ 100M">04 var !oras/tag = xml5oc.get.lements1,;ag<ame2"#ronostico/!oras"3=0>.get.lements1,;ag<ame2"!ora"34 "or 2var i = 04 i < !oras/tag.lengt!4 i??3 9 :)tenemos los datos !orarios Due nos interesen var "ec!a = !oras/tag=i>.get.lements1,;ag<ame2""ec!a"3=0>.c!ild<odes=0>.node@alue4 var !ora/datos = !oras/tag=i>.get.lements1,;ag<ame2"!ora/datos"3=0>.c!ild<odes=0>.node@alue4 var tem#eratura = !oras/tag=i>.get.lements1,;ag<ame2"tem#eratura"3=0>.c!ild<odes=0>.node@alue4 var texto = !oras/tag=i>.get.lements1,;ag<ame2"texto"3=0>.c!ild<odes=0>.node@alue4 var !umedad = !oras/tag=i>.get.lements1,;ag<ame2"!umedad"3=0>.c!ild<odes=0>.node@alue4 var #resion = !oras/tag=i>.get.lements1,;ag<ame2"#resion"3=0>.c!ild<odes=0>.node@alue4 var icono = !oras/tag=i>.get.lements1,;ag<ame2"icono"3=0>.c!ild<odes=0>.node@alue4 var viento = !oras/tag=i>.get.lements1,;ag<ame2"viento"3=0>.c!ild<odes=0>.node@alue4 var dir/viento = !oras/tag=i>.get.lements1,;ag<ame2"dir/viento"3=0>.c!ild<odes=0>.node@alue4 var ico/viento = !oras/tag=i>.get.lements1,;ag<ame2"ico/viento"3=0>.c!ild<odes=0>.node@alue4 var km! = 004 var div/dias = document.get.lement1,*d20dias034 var div/!oras = document.get.lement1,*d20!oras034 var xml5oc = cargar6&75oc20HJF8.xml034

) 9 2 0 2 ) 2 2

i"2is<um)er2viento339km! = 0 km !04B

*m#rimirAorasAtml ?= 0<tr><td>0?!ora/datos?0< td><td>0?tem#eratura?0 Ldeg4(< td><td><img src="0?icono? !Na< td><td>0?viento?km!?0< td><td>0?dir/viento?0< td>< tr>04 B *m#rimirAorasAtml ?= 0< ta)le>04 div/!oras.innerA;&7 = *m#rimirAorasAtml4

var *m#rimir5iasAtml = 0<ta)le cell#adding="0" cells#acing="0" st,le="%idt!$ 100M">04

2 ( 2 % 2 * 2 & 2 7 2 ' 2 9 ( 0 ( ) ( 2 ( ( ( % (

var dias/tag = xml5oc.get.lements1,;ag<ame2"#ronostico/dias"3=0>.get.lements1,;ag<ame2"dia"34 "or 2var i = 04 i < dias/tag.lengt!4 i??3 9 :)tenemos los datos !orarios Due nos interesen var "ec!a = dias/tag=i>.get.lements1,;ag<ame2""ec!a"3=0>.c!ild<odes=0>.node@alue4 var "ec!a/larga = dias/tag=i>.get.lements1,;ag<ame2""ec!a/larga"3=0>.c!ild<odes=0>.node@alue4 var tem#/maxima = dias/tag=i>.get.lements1,;ag<ame2"tem#/maxima"3=0>.c!ild<odes=0>.node@alue4 var tem#/minima = dias/tag=i>.get.lements1,;ag<ame2"tem#/minima"3=0>.c!ild<odes=0>.node@alue4 var icono = dias/tag=i>.get.lements1,;ag<ame2"icono"3=0>.c!ild<odes=0>.node@alue4 var texto = dias/tag=i>.get.lements1,;ag<ame2"texto"3=0>.c!ild<odes=0>.node@alue4 var !umedad = dias/tag=i>.get.lements1,;ag<ame2"!umedad"3=0>.c!ild<odes=0>.node@alue4 var viento = dias/tag=i>.get.lements1,;ag<ame2"viento"3=0>.c!ild<odes=0>.node@alue4 var dir/viento = dias/tag=i>.get.lements1,;ag<ame2"dir/viento"3=0>.c!ild<odes=0>.node@alue4 var ico/viento = dias/tag=i>.get.lements1,;ag<ame2"ico/viento"3=0>.c!ild<odes=0>.node@alue4 var salida/sol = dias/tag=i>.get.lements1,;ag<ame2"salida/sol"3=0>.c!ild<odes=0>.node@alue4 var #uesta/sol = dias/tag=i>.get.lements1,;ag<ame2"#uesta/sol"3=0>.c!ild<odes=0>.node@alue4 var salida/luna = dias/tag=i>.get.lements1,;ag<ame2"salida/luna"3=0>.c!ild<odes=0>.node@alue4 var #uesta/luna = dias/tag=i>.get.lements1,;ag<ame2"#uesta/luna"3=0>.c!ild<odes=0>.node@alue4 var ico/"ase/luna = dias/tag=i>.get.lements1,;ag<ame2"ico/"ase/luna"3=0>.c!ild<odes=0>.node@alue4 var km! = 004 i"2is<um)er2viento339km! = 0 km !04B

*m#rimir5iasAtml ?= 0<tr><td>0?"ec!a/larga?0< td><td><img src="0?icono?0" title="0?texto?0" >< td><td Ldeg4(< td><td>0?!umedad?0M< td><td>0?viento?km!?0< td><td>0?dir/viento?0< td>< tr>04

* ( & ( 7 ( ' ( 9 % 0 % ) % 2 % ( % % % * % & % 7 % ' % 9 * 0 *

B *m#rimir5iasAtml ?= 0< ta)le>04 div/dias.innerA;&7 = *m#rimir5iasAtml4 B

"unction cargar6&75oc2arc!ivo6&73 9 var xml5oc4 i" 2%indo%.6&7Att#CeDuest3 9 code "or *.J?E Kire"oxE (!romeE :#eraE Oa"ari xml!tt#=ne% 6&7Att#CeDuest234 B else 9 code "or *.FE *.5 xml!tt#=ne% Gctive6:)-ect2"&icroso"t.6&7A;;N"34 B xml!tt#.o#en2"G.;"Earc!ivo6&7E"alse34 xml!tt#.send234 xml5oc=xml!tt#.res#onse6&74 return xml5oc4 B < scri#t>

) * 2 * ( * % * * * & * 7 * ' * 9 & 0 & ) & 2 & ( & % & * & & &

7 & ' & 9 7 0 7 ) 7 2 7 ( 7 % 7 * 7 & 7 7


Como puedes compro%ar es realmente sencillo realizar la integracin con simple cdigo javascript, puedes ver este ejemplo "uncionando en& 'jemplo Javascript ( XML )utiempo

4. Leer XML en Javascript


/%- ttp-88elcaminillo.wordpress.com835638568698leer:*ml:en:javascript8

;lguna que otra ve), puede que tengamos que leer alg<n &ic ero XML con javascript. %ntonces descubrir+n que, =>1mo no?, cada navegador tiene sus instrucciones de uso.

>uando por &in lo conseguir en @ire&o* y A% descubr! que sa&ari y c rome eran otro mundo. Bracias a esta web ttp-88c romespot.com8&orum8google:c rome:troubles ooting865C7:*ml:load:issue: javascript. tml "un &oro$ encontr mi soluci1n y entre eso y la que ya ten!a de est+ otra web me ice mi propia &uncioncilla para leer XML. D adem+s e preparado un ejemplillo para que veamos su uso. 2ara ello vamos a leer un &ic ero *ml con javascript y dibujar su contenido en una tabla creada din+micamente. 6: %l &ic ero XML

) 2 ( % * & 7 ' 9 )0 )) )2 )( )% )* )& )7 )'

<?xml version="1.0" encoding="P;K-8"?> <eventos> <evento> <"ec!a>01 0H I01I< "ec!a> <!ora>I0$00< !ora> <comentario>(ine< comentario> < evento> <evento> <"ec!a>01 1J I01I< "ec!a> <!ora>08$00< !ora> <comentario>(arrera &atutina< comentario> < evento> <evento> <"ec!a>01 1J I01I< "ec!a> <!ora>19$00< !ora> <comentario>.nsa,o del coro< comentario> < evento> < eventos>

3: %l &ic ero tratarXML.js E que contiene la &unci1n para abrir el javascript

) 2 ( % * & 7 ' 9 )0 )) )2 )( )% )* )& )7 )' )9 20 2) 22 2(

"unction G)rirKic!ero2"ic!6&73 9 var xml5oc=unde"ined4 tr, 9 i" 2document.all3 *. 9 xml5oc = ne% Gctive6:)-ect2"&icroso"t.6&75:&"34 B else "ire"ox 9 xml5oc = document.im#lementation.create5ocument2""E""Enull34 B xml5oc.as,nc="alse4 xml5oc.load2"ic!6&734

otros sa"ariE c!rome var xml!tt# = ne% %indo%.6&7Att#CeDuest234 xml!tt#.o#en2"G.;"E"ic!6&7E"alse34 xml!tt#.send2null34 xml5oc = xml!tt#.res#onse6&7.document.lement4

B catc!2e3 9 tr, 9

2% 2* 2& 27 2' 29 (0 () (2 (( (% (*

return xml5oc4 B catc! 2e3 9 return unde"ined4 B B return xml5oc4

7: %l &ic ero- calendario.js E almacenar+ los datos del *ml y lo imprimir+ en una tabla creada en javascript creada din+micamente.

) 2 ( % * & 7 ' 9 ) 0 ) ) ) 2 ) ( ) % ) * ) & ) 7 ) ' ) 9 2 0 2 ) 2 2

"unction .vento2"ec!aE!oraEcomentario3 9 t!is."ec!a = "ec!a4 t!is.!ora = !ora4 t!is.comentario = comentario4 B "unction (argar6&7.ventos23 9 tr, 9 xml5oc=G)rirKic!ero2"calendario.xml"34 eventos6&7=xml5oc.get.lements1,;ag<ame20evento034 i" 2eventos6&7.lengt!>03 9 eventos=ne% Grra,234 clase con los datos cargados B "or2var i=04 i< eventos6&7.lengt!4 i??3 9 xml.vento=eventos6&7=i>4

"ec!a=xml.vento.get.lements1,;ag<ame2""ec!a"3=0>."irst(!ild.node@alue4 !ora=xml.vento.get.lements1,;ag<ame2"!ora"3=0>."irst(!ild.node@alue4 comentario=xml.vento.get.lements1,;ag<ame2"comentario"3=0>."irst(!ild.n evento = ne% .vento2"ec!aE!oraEcomentario34 eventos.#us!2evento34 B return eventos4

B catc!2e3 9 alert2"Oe #rodu-o un error en la carga de los datos"34 B B "unction crear;a)la23 9 var tr4 var td4 var ta)la4 var l=04

2 ( 2 % 2 * 2 & 2 7 2 ' 2 9 ( 0 ( ) ( 2 ( B ( ( % ( * ( & ( 7 ( ' ( 9 % 0 % ) % 2 % ( % % % * % & % 7

ev= (argar6&7.ventos234 auxPn.ven=ev.#o#234 ta)la=document.get.lement1,*d2"datos"34 %!ile 2auxPn.ven8=unde"ined3 9 tr=ta)la.insertCo%2l34 creamos las columnas de la ta)la td=tr.insert(ell2034 td.innerA;&7=auxPn.ven."ec!a4 td=tr.insert(ell2134 td.innerA;&7=auxPn.ven.!ora4 td=tr.insert(ell2I34 td.innerA;&7=auxPn.ven.comentario4 l??4 auxPn.ven=ev.#o#234 B i" 2l==03 9 ta)la=document.get.lement1,*d2"datos"34 tr=ta)la.insertCo%2l34 td=tr.insert(ell2034 td.innerA;&7=" <o Aa, .ventos "4 B

% ' % 9 * 0 * ) * 2 * ( * % * * * & * 7 * ' * 9 & 0 & ) & 2 & ( & % & * & & & 7
F: Ande*. tml E nuestra p+gina

) 2 ( % * & 7 '

<85:(;QN. !tml NP17*( "- RH( 5;5 6A;&7 1.0 ;ransitional .<" "5;5 x!tml1-transitional.dtd"> <!tml xmlns="!tt#$ %%%.%H.org 1999 x!tml"> <!ead> <title>.-em#lo 6&7< title> <meta !tt#-eDuiv="(ontent-;,#e" content="text !tml4 c!arset=ut"-8" > <scri#t t,#e="text -avascri#t"

9 )0 )) )2 )( )% )* )& )7 )'

src="calendario.-s">< scri#t> <scri#t t,#e="text -avascri#t" src="tratar6&7.-s">< scri#t> < !ead> <)od,> <ta)le id="datos"> <scri#t t,#e="text -avascri#t"> crear;a)la234 < scri#t> < ta)le> < )od,> < !tml>

@uentes-

ttp-88www.*ml.com8pub8a8355985385G8*ml: ttp:request. tml ttp-88c romespot.com8&orum8google:c rome:troubles ooting865C7:*ml:load:issue:javascript. tml ttp-88www.w7sc ools.com8*ml8*mlH ttp.asp

5. XMLHttpRequest functions
show page contents DE: http://www.quirksmode.org/js/xmlhttp.html

See section *+, o" the %oo-. This is the XMLHttpRequest function I always use; seequirksmode.js the script file that!s used in e"ery pa#e on this site. It is presented "ery shortly; section $%& of the 'ook treats these functions in detail.

CeDuest2urlEcall)ackE#ost5ata3 9

var reD = create6&7A;;N:)-ect234

i" 28reD3 return4

var met!od = 2#ost5ata3 ? "N:O;" $ "G.;"4

reD.o#en2met!odEurlEtrue34

reD.setCeDuestAeader20Pser-Ggent0E06&7A;;N 1.0034

i" 2#ost5ata3

reD.setCeDuestAeader20(ontent-t,#e0E0a##lication x-%%%-"orm-urlencoded034

reD.onread,statec!ange = "unction 23 9

i" 2reD.read,Otate 8= S3 return4

i" 2reD.status 8= I00 LL reD.status 8= H0S3 9

alert20A;;N error 0 ? reD.status34

return4

call)ack2reD34

i" 2reD.read,Otate == S3 return4

reD.send2#ost5ata34

ctories = =

"unction 23 9return ne% 6&7Att#CeDuest23BE

"unction 23 9return ne% Gctive6:)-ect2"&sxmlI.6&7A;;N"3BE

"unction 23 9return ne% Gctive6:)-ect2"&sxmlH.6&7A;;N"3BE

"unction 23 9return ne% Gctive6:)-ect2"&icroso"t.6&7A;;N"3B

te6&7A;;N:)-ect23 9

var xml!tt# = "alse4

"or 2var i=04i<6&7Att#Kactories.lengt!4i??3 9

tr, 9

xml!tt# = 6&7Att#Kactories=i>234

catc! 2e3 9

continue4

)reak4

return xml!tt#4

.t/s used li-e this&

"ile.txt0E!andleCeDuest34

0o1 the "ile "ile.txt is "etched, and 1hen that/s done the "unction !andleCeDuest23 is called. )his "unction receives the XML2ttp3e#uest o%ject as an argument, 1hich . traditionall! call reD4though, o" course, !ou can use an! varia%le name !ou li-e5. )!picall!, this "unction reads out the res#onse6&7 or res#onse;ext and does something 1ith it.

leCeDuest2reD3 9

var %riteroot = =some element>4

%riteroot.innerA;&7 = reD.res#onse;ext4

(ne o'ject per request


)his "unction creates a ne1 XML2ttp3e#uest o%ject "or ever! re#uest !ou ma-e. .n simple cases such as this site, 1here ever! page "etches onl! three to "ive "iles, . don/t mind creating three to "ive o%jects. .n more comple6 sites, ho1ever, 1here an! page can ma-e an ar%itrar! amount o" re#uests, it/s pro%a%l! %etter to 1rite a "unction that reuses e6isting XML2ttp3e#uest o%jects.

Anda mungkin juga menyukai