Ajax Json shows nothing

0

I'm following a tutorial, but the page does not show anything. index.html

        <html>
<head></head>
<body>
    <button onclick="ajax_get_json()">Mostrar datos</button>
    <div id="info"></div>

    <script type="text/javascript">
        var resultado = document.getElementById("info");

        function ajax_get_json(){
            var xmlhttp;

            /*
            if(window.XMLHttpRequest){
                xmlhttp = new XMLHttpRequest();
            }else{
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            } */

            if(window.XMLHttpRequest) /*Vemos si el objeto window posee el metodo XMLHttpRequest(Navegadores como Mozilla y Safari).*/
            {
                xmlhttp = new XMLHttpRequest(); //Si lo tiene, crearemos el objeto
            }  

            else if(window.ActiveXObject) /*Sino tenia el metodo anterior,deberia ser el Internet Exp.*/
            {
                var versionesObj = new Array(
                                            'Msxml2.XMLHTTP.5.0',
                                            'Msxml2.XMLHTTP.4.0',
                                            'Msxml2.XMLHTTP.3.0',
                                            'Msxml2.XMLHTTP',
                                            'Microsoft.XMLHTTP');

                for (var i = 0; i < versionesObj.length; i++)
                {
                    try
                        {
                            xmlhttp = new ActiveXObject(versionesObj[i]);
                        }
                        catch (errorControlado)
                        {

                        }
                }
            }
            throw new Error("No se pudo crear el objeto XMLHttpRequest");

            xmlhttp.onreadystatechange = function(){                
                if(xmlhttp.readystate === 4 && xmlhttp.status === 200){
                    var datos = JSON.parse(xmlhttp.responseText);

                    for(var i in datos){
                        resultado.innerHTML += i + ": " + datos[i] + "<br/>"
                    }
                }
            }

            xmlhttp.open("GET", "datos.json", false);
            xmlhttp.send();

        }
    </script>
</body>
</html>
    
asked by Jhon Hernández 23.06.2018 в 09:46
source

1 answer

0

Compare your code with this solution, I wrote it when I needed to manage ajax, without using third-party libraries, and it has been very useful for me:

First build a class that can be invoked from anywhere

<!-- language: lang-js -->  
// Se define un objeto que centraliza todos los llamados  
// para obviar eventuales conflictos de espacios de nombres  
var llamadorAJAX = new Object();  

// Se asignan constantes para control de estatus  
llamadorAJAX.READY_STATE_UNINITIALIZED = 0;  
llamadorAJAX.READY_STATE_LOADING = 1;  
llamadorAJAX.READY_STATE_LOADED = 2;  
llamadorAJAX.READY_STATE_INTERACTIVE = 3;  
llamadorAJAX.READY_STATE_COMPLETE = 4;  
// Respuesta satisfactoria del servidor  
llamadorAJAX.LOAD_STATUS_SUCCESS = 200;  
// Método constructor  
llamadorAJAX.CargadordeContenidos = function(url, accion, OnloadcallBack,  
                                    OnErrorCallBack, data,  
                                    encodeProtocol) 
{  
    this.url = url;
    this.xhr = null; // objeto request
    this.method = (accion) ? accion : "GET";
    if (encodeProtocol){
        this.encodeProtocol = encodeProtocol;
    }else{
        if(this.method=="POST"){
            this.encodeProtocol = "application/x-www-form-urlencoded";
        }else{
            this.encodeProtocol = null;
        }
    } 
    this.data = (data) ? data : null;
    this.onload = OnloadcallBack;
    this.onerror = (OnErrorCallBack) ? OnErrorCallBack : 
                                       this.defaultError;
    this.cargaContenidoAJAX(url);
} 
// Ahora ajustes en el prototipo del lanzador de solicitudes
llamadorAJAX.CargadordeContenidos.prototype = {
cargaContenidoAJAX: function(url) {
    if(window.XMLHttpRequest){
        this.xhr = new XMLHttpRequest();
    }else{
        if(window.ActiveXObject) {
            this.xhr = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    if(this.xhr){
        try{
            var loader = this;
            this.xhr.onreadystatechange = function() {
                loader.onReadyState.call(loader);
            }
            this.xhr.open(this.method, url, true);
            // si el metodo es POST es necesario que encodeprotocol se haya establecido
            if (this.encodeProtocol){
                this.xhr.setRequestHeader("Content-Type", this.encodeProtocol);
            }
            this.xhr.send(this.data);
        }catch(err){
            this.onerror.call(this);
        }        
    }
},
onReadyState: function() {
    var xhr = this.xhr;
    var ready = xhr.readyState;
    // interesa atrapar estado complete
    if (ready==llamadorAJAX.READY_STATE_COMPLETE){
        var httpStatus = xhr.status;
        // verifica la condicion del resultado
        if ((httpStatus == llamadorAJAX.LOAD_STATUS_SUCCESS) || (httpStatus == 0)){
            this.onload.call(this);
        }else{
            this.onerror.call(this);
        }
    }
},
defaultError: function() {
    alert("Se ha producido un error al obtener los datos"
        + "\n\nreadyState:" + this.req.readyState
        + "\nstatus: " + this.xhr.status
        + "\nheaders: " + this.xhr.getAllResponseHeaders());
}}

Now its use
Write a method to show general errors (if necessary) and at least one method to handle Ajax returns like this:

function retrollamado_mostrar_respuesta_ajax(){
    var respuesta = ''+ this.xhr.responseText;
    // Hacer lo que se quiera con la respuesta
}

And, to execute the requests

// Declarar la dirección que atiende la solisitud ajax
var url = 'http://www.misitio.com/ajaxresponser.html'; // o
var url = 'http://www.misitio.com/index.php?q=ajaxresponser'; // o etc
// Recoger los datos a pasar
var data = miMetodoParaRecogerData();
// Ejecutar el llamado
var dummie = new llamadorAJAX.CargadordeContenidos(url, "POST",  
           retrollamado_mostrar_respuesta_ajax, null, data);

And it's not anymore. Now you have a utility that handles all your requests.

    
answered by 25.06.2018 в 20:49