elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Arreglado, de nuevo, el registro del warzone (wargame) de EHN


+  Foro de elhacker.net
|-+  Programación
| |-+  Desarrollo Web (Moderador: #!drvy)
| | |-+  Cargar XML desde un servidor externo
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Cargar XML desde un servidor externo  (Leído 1,645 veces)
Gangatravel

Desconectado Desconectado

Mensajes: 1


Ver Perfil
Cargar XML desde un servidor externo
« en: 31 Julio 2015, 00:10 am »

Hola, me descarge unos ejemplos de prueba para cargar un XML desde otro servidor diferente al mio pero cuando cambio la ruta del XML no me funciona, los archivos que tengo son estos:

HTML:

Código
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Cross XML Sample</title>
  5.  
  6. <meta name="viewport" content="width=device-width, initial-scale=1">
  7.  
  8. <link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.css" />
  9. <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
  10. <script src="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.js"></script>
  11. <script src="xml2json.js"></script>
  12. <script src="jquery.xdomainajax.js"></script>
  13. // For This example, im going to use sample xml from o'reily for practice
  14. // located at url http://examples.oreilly.com/9780596002527/examples/first.xml
  15. // We are going to extract character name nodes for this sample  
  16. function xmlLoader(){
  17. $.ajax({
  18.    url: 'http://examples.oreilly.com/9780596002527/examples/first.xml',
  19.    dataType: "xml",
  20.    type: 'GET',
  21.    success: function(res) {
  22. var myXML = res.responseText;
  23. // This is the part xml2Json comes in.
  24. var JSONConvertedXML = $.xml2json(myXML);
  25. $('#myXMLList').empty();
  26. for(var i = 0; i < JSONConvertedXML.book.character.length; i++){
  27. $('#myXMLList').append('<li><a href="#">'+JSONConvertedXML.book.character[i].name+'</a></li>')
  28. }
  29. $('#myXMLList').listview('refresh');
  30. $.mobile.hidePageLoadingMsg();
  31.    }
  32. });
  33. }
  34.  
  35. $( document ).delegate("#home", "pageshow", function() {
  36. $.mobile.showPageLoadingMsg();
  37.   xmlLoader();
  38. });
  39. </script>
  40. </head>
  41.  
  42. <body>
  43. <div data-role="page" id="home">
  44. <div data-role="content">
  45. <ul data-role="listview" data-theme="c" id="myXMLList">
  46. </ul>
  47. </div>
  48. </div>
  49. </body>
  50. </html>

JS:

Código
  1. jQuery.ajax = (function(_ajax){
  2.  
  3.    var protocol = location.protocol,
  4.        hostname = location.hostname,
  5.        exRegex = RegExp(protocol + '//' + hostname),
  6.        YQL = 'http' + (/^https/.test(protocol)?'s':'') + '://query.yahooapis.com/v1/public/yql?callback=?',
  7.        query = 'select * from xml where url="{URL}"';
  8.  
  9.    function isExternal(url) {
  10.        return !exRegex.test(url) && /:\/\//.test(url);
  11.    }
  12.  
  13.    return function(o) {
  14.  
  15.        var url = o.url;
  16.  
  17.        if ( /get/i.test(o.type) && !/json/i.test(o.dataType) && isExternal(url) ) {
  18.  
  19.            // Manipulate options so that JSONP-x request is made to YQL
  20.  
  21.            o.url = YQL;
  22.            o.dataType = 'json';
  23.  
  24.            o.data = {
  25.                q: query.replace(
  26.                    '{URL}',
  27.                    url + (o.data ?
  28.                        (/\?/.test(url) ? '&' : '?') + jQuery.param(o.data)
  29.                    : '')
  30.                ),
  31.                format: 'xml'
  32.            };
  33.  
  34.            // Since it's a JSONP request
  35.            // complete === success
  36.            if (!o.success && o.complete) {
  37.                o.success = o.complete;
  38.                delete o.complete;
  39.            }
  40.  
  41.            o.success = (function(_success){
  42.                return function(data) {
  43.  
  44.                    if (_success) {
  45.                        // Fake XHR callback.
  46.                        _success.call(this, {
  47.                            responseText: (data.results[0] || '')
  48.                                // YQL screws with <script>s
  49.                                // Get rid of them
  50.                                .replace(/<script[^>]+?\/>|<script(.|\s)*?\/script>/gi, '')
  51.                        }, 'success');
  52.                    }
  53.  
  54.                };
  55.            })(o.success);
  56.  
  57.        }
  58.  
  59.        return _ajax.apply(this, arguments);
  60.  
  61.    };
  62.  
  63. })(jQuery.ajax);

JS (2):

Código
  1. ;if(window.jQuery) (function($){
  2.  
  3. // Add function to jQuery namespace
  4. $.extend({
  5.  
  6.  // converts xml documents and xml text to json object
  7.  xml2json: function(xml, extended) {
  8.   if(!xml) return {}; // quick fail
  9.  
  10.   //### PARSER LIBRARY
  11.   // Core function
  12.   function parseXML(node, simple){
  13.    if(!node) return null;
  14.    var txt = '', obj = null, att = null;
  15.    var nt = node.nodeType, nn = jsVar(node.localName || node.nodeName);
  16.    var nv = node.text || node.nodeValue || '';
  17.    /*DBG*/ //if(window.console) console.log(['x2j',nn,nt,nv.length+' bytes']);
  18.    if(node.childNodes){
  19.     if(node.childNodes.length>0){
  20.      /*DBG*/ //if(window.console) console.log(['x2j',nn,'CHILDREN',node.childNodes]);
  21.      $.each(node.childNodes, function(n,cn){
  22.       var cnt = cn.nodeType, cnn = jsVar(cn.localName || cn.nodeName);
  23.       var cnv = cn.text || cn.nodeValue || '';
  24.       /*DBG*/ //if(window.console) console.log(['x2j',nn,'node>a',cnn,cnt,cnv]);
  25.       if(cnt == 8){
  26.        /*DBG*/ //if(window.console) console.log(['x2j',nn,'node>b',cnn,'COMMENT (ignore)']);
  27.        return; // ignore comment node
  28.       }
  29.       else if(cnt == 3 || cnt == 4 || !cnn){
  30.        // ignore white-space in between tags
  31.        if(cnv.match(/^\s+$/)){
  32.         /*DBG*/ //if(window.console) console.log(['x2j',nn,'node>c',cnn,'WHITE-SPACE (ignore)']);
  33.         return;
  34.        };
  35.        /*DBG*/ //if(window.console) console.log(['x2j',nn,'node>d',cnn,'TEXT']);
  36.        txt += cnv.replace(/^\s+/,'').replace(/\s+$/,'');
  37. // make sure we ditch trailing spaces from markup
  38.       }
  39.       else{
  40.        /*DBG*/ //if(window.console) console.log(['x2j',nn,'node>e',cnn,'OBJECT']);
  41.        obj = obj || {};
  42.        if(obj[cnn]){
  43.         /*DBG*/ //if(window.console) console.log(['x2j',nn,'node>f',cnn,'ARRAY']);
  44.  
  45. // http://forum.jquery.com/topic/jquery-jquery-xml2json-problems-when-siblings-of-the-same-tagname-only-have-a-textnode-as-a-child
  46. if(!obj[cnn].length) obj[cnn] = myArr(obj[cnn]);
  47. obj[cnn] = myArr(obj[cnn]);
  48.  
  49. obj[cnn][ obj[cnn].length ] = parseXML(cn, true/* simple */);
  50.         obj[cnn].length = obj[cnn].length;
  51.        }
  52.        else{
  53.         /*DBG*/ //if(window.console) console.log(['x2j',nn,'node>g',cnn,'dig deeper...']);
  54.         obj[cnn] = parseXML(cn);
  55.        };
  56.       };
  57.      });
  58.     };//node.childNodes.length>0
  59.    };//node.childNodes
  60.    if(node.attributes){
  61.     if(node.attributes.length>0){
  62.      /*DBG*/ //if(window.console) console.log(['x2j',nn,'ATTRIBUTES',node.attributes])
  63.      att = {}; obj = obj || {};
  64.      $.each(node.attributes, function(a,at){
  65.       var atn = jsVar(at.name), atv = at.value;
  66.       att[atn] = atv;
  67.       if(obj[atn]){
  68.        /*DBG*/ //if(window.console) console.log(['x2j',nn,'attr>',atn,'ARRAY']);
  69.  
  70. // http://forum.jquery.com/topic/jquery-jquery-xml2json-problems-when-siblings-of-the-same-tagname-only-have-a-textnode-as-a-child
  71. //if(!obj[atn].length) obj[atn] = myArr(obj[atn]);//[ obj[ atn ] ];
  72.        obj[cnn] = myArr(obj[cnn]);
  73.  
  74. obj[atn][ obj[atn].length ] = atv;
  75.        obj[atn].length = obj[atn].length;
  76.       }
  77.       else{
  78.        /*DBG*/ //if(window.console) console.log(['x2j',nn,'attr>',atn,'TEXT']);
  79.        obj[atn] = atv;
  80.       };
  81.      });
  82.      //obj['attributes'] = att;
  83.     };//node.attributes.length>0
  84.    };//node.attributes
  85.    if(obj){
  86.     obj = $.extend( (txt!='' ? new String(txt) : {}),/* {text:txt},*/ obj || {}/*, att || {}*/);
  87.     txt = (obj.text) ? (typeof(obj.text)=='object' ? obj.text : [obj.text || '']).concat([txt]) : txt;
  88.     if(txt) obj.text = txt;
  89.     txt = '';
  90.    };
  91.    var out = obj || txt;
  92.    //console.log([extended, simple, out]);
  93.    if(extended){
  94.     if(txt) out = {};//new String(out);
  95.     txt = out.text || txt || '';
  96.     if(txt) out.text = txt;
  97.     if(!simple) out = myArr(out);
  98.    };
  99.    return out;
  100.   };// parseXML
  101.   // Core Function End
  102.   // Utility functions
  103.   var jsVar = function(s){ return String(s || '').replace(/-/g,"_"); };
  104.  
  105. // NEW isNum function: 01/09/2010
  106. // Thanks to Emile Grau, GigaTecnologies S.L., www.gigatransfer.com, www.mygigamail.com
  107. function isNum(s){
  108. // based on utility function isNum from xml2json plugin (http://www.fyneworks.com/ - diego@fyneworks.com)
  109. // few bugs corrected from original function :
  110. // - syntax error : regexp.test(string) instead of string.test(reg)
  111. // - regexp modified to accept  comma as decimal mark (latin syntax : 25,24 )
  112. // - regexp modified to reject if no number before decimal mark  : ".7" is not accepted
  113. // - string is "trimmed", allowing to accept space at the beginning and end of string
  114. var regexp=/^((-)?([0-9]+)(([\.\,]{0,1})([0-9]+))?$)/
  115. return (typeof s == "number") || regexp.test(String((s && typeof s == "string") ? jQuery.trim(s) : ''));
  116. };
  117. // OLD isNum function: (for reference only)
  118. //var isNum = function(s){ return (typeof s == "number") || String((s && typeof s == "string") ? s : '').test(/^((-)?([0-9]*)((\.{0,1})([0-9]+))?$)/); };
  119.  
  120.   var myArr = function(o){
  121.  
  122. // http://forum.jquery.com/topic/jquery-jquery-xml2json-problems-when-siblings-of-the-same-tagname-only-have-a-textnode-as-a-child
  123. //if(!o.length) o = [ o ]; o.length=o.length;
  124.    if(!$.isArray(o)) o = [ o ]; o.length=o.length;
  125.  
  126. // here is where you can attach additional functionality, such as searching and sorting...
  127.    return o;
  128.   };
  129.   // Utility functions End
  130.   //### PARSER LIBRARY END
  131.  
  132.   // Convert plain text to xml
  133.   if(typeof xml=='string') xml = $.text2xml(xml);
  134.  
  135.   // Quick fail if not xml (or if this is a node)
  136.   if(!xml.nodeType) return;
  137.   if(xml.nodeType == 3 || xml.nodeType == 4) return xml.nodeValue;
  138.  
  139.   // Find xml root node
  140.   var root = (xml.nodeType == 9) ? xml.documentElement : xml;
  141.  
  142.   // Convert xml to json
  143.   var out = parseXML(root, true /* simple */);
  144.  
  145.   // Clean-up memory
  146.   xml = null; root = null;
  147.  
  148.   // Send output
  149.   return out;
  150.  },
  151.  
  152.  // Convert text to XML DOM
  153.  text2xml: function(str) {
  154.   // NOTE: I'd like to use jQuery for this, but jQuery makes all tags uppercase
  155.   //return $(xml)[0];
  156.   var out;
  157.   try{
  158.    var xml = ($.browser.msie)?new ActiveXObject("Microsoft.XMLDOM"):new DOMParser();
  159.    xml.async = false;
  160.   }catch(e){ throw new Error("XML Parser could not be instantiated") };
  161.   try{
  162.    if($.browser.msie) out = (xml.loadXML(str))?xml:false;
  163.    else out = xml.parseFromString(str, "text/xml");
  164.   }catch(e){ throw new Error("Error parsing XML string") };
  165.   return out;
  166.  }
  167.  
  168. }); // extend $
  169.  
  170. })(jQuery);

Alguien sabe que he de cambiar para que cuando cambie la ruta del XML que hay en el codigo html por la del XML que quiero utilizar funcione?


Mod: Los códigos deben ir en etiquetas GeSHi


« Última modificación: 31 Julio 2015, 07:08 am por engel lex » En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Como listar directorios de un servidor externo
Dudas Generales
Dacan 3 3,946 Último mensaje 29 Julio 2010, 16:19 pm
por Dacan
Conexión ASP.Net con SQL Server en servidor externo
.NET (C#, VB.NET, ASP)
DjFlo 1 4,176 Último mensaje 23 Abril 2013, 12:25 pm
por DjFlo
No es posible conectar a servidor externo.
Redes
NikNitro! 2 2,011 Último mensaje 28 Mayo 2014, 17:04 pm
por NikNitro!
No puedo conectar con servidor externo « 1 2 »
Redes
Maykel23 13 6,677 Último mensaje 9 Junio 2016, 19:22 pm
por Maykel23
Enviar imagen a servidor externo javascript
Programación General
OssoH 2 1,967 Último mensaje 24 Febrero 2017, 15:48 pm
por OssoH
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines