Aproveitando uma dúvida do fórum do jQuery, escrevi um script para trabalhar com xml retornado via ajax. Vamos por partes:
Nome do script: (xml.php)
Ajax. Este script, valendo-se da condição, escreve um xml válido.
<?php if ($_GET['xml']) { header("Content-type: text/xml; charset=ISO-8859-1"); echo ' <empresa> <funcionario> <id>10</id> <nome>Fulano</nome> <salario>1600</salario> <cargo>Analista de sistemas</cargo> <depto>Tecnologia da informao</depto> </funcionario> <funcionario> <id>14</id> <nome>Beltrano</nome> <salario>1900</salario> <cargo>Suporte Help Desk</cargo> <depto>Tecnologia da informao</depto> </funcionario> <funcionario> <id>24</id> <nome>Cicrano</nome> <salario>2000</salario> <cargo>Compradora Lar</cargo> <depto>Compras/Lar</depto> </funcionario> <funcionario> <id>34</id> <nome>Teste</nome> <salario>3900</salario> <cargo>Gerente E-Commerce</cargo> <depto>Comrcio Eletrnico</depto> </funcionario> <funcionario> <id>44</id> <nome>zefina</nome> <salario>3900</salario> <cargo>Design Modas</cargo> <depto>Vendas</depto> </funcionario> </empresa>'; sleep(1); exit; }
JavaScript – parte legal 🙂 :
$(document).ready(function(){ var loading = '<span>Aguarde...</span>'; var $button = $('button'); var click = false; // extend, para aplicar um zebra table $.fn.zebra = function() { $('tbody tr:visible',this) .filter(':odd').removeClass('even').addClass('odd') .end() .filter(':even').removeClass('odd').addClass('even'); return this; } $().ajaxStart( function(){ $button.after(loading) } ).ajaxStop( function(){ $button.next().fadeOut('fast',function(){ $(this).remove(); }) } ); $button.bind('click',function(){ if (click) return; click = true; $.ajax({ type: 'GET', url: 'xml.php?xml=1', dataType: 'xml', success: function(xml) { var $table = $('table').find('tbody').empty().end(); var $tr = null; $('funcionario',xml).each(function(){ $tr = document.createElement('tr'); $($tr).hover( function(){ $(this).addClass('hover') }, function(){ $(this).removeClass('hover') } ).bind('click',function(){ alert($('td:first',this).text()) }); $(this).children().each(function(){ $($tr).append('<td>'+$(this).text()+'</td>'); }); $table.append($tr); }); $table.zebra().find('tfoot td').text('time: '+new Date().getTime()).end().parent().show(); click = false; } }); }); });
HTML
<style> table { background:#fff;border:1px solid #dadada;width:500px;} table tbody tr {cursor:default;} table tfoot tr {background:#ccc;} .odd {background:#eee;} .even {background:#f6f6f6;} .hover {background:#fff000;} </style> <body> <button>Get XML</button> <div id="result" style="display:none"> <table border="0" cellpadding="2" cellspacing="1"> <thead style="background:#ccc"> <tr> <th>id</th> <th>nome</th> <th>salario</th> <th>cargo</th> <th>dpto</th> </tr> </thead> <tbody> </tbody> <tfoot> <tr> <td colspan="5"></td> </tr> </tfoot> </table> </div>
Adicionei alguns efeitos para melhorar a visualização (zebra e hover)
[s]
JunioR