2010-06-14 35 views
118

Me gustaría saber cómo usar XMLHttpRequest para cargar el contenido de una URL remota y tener el HTML del sitio accedido almacenado en una variable JS.¿Cómo obtener la respuesta de XMLHttpRequest?

Digamos, si quisiera cargar y alertar() el HTML de http://foo.com/bar.php, ¿cómo lo haría?

+0

posible duplicado de [¿Qué me falta en el XMLHttp ¿Solicitar?] (Http://stackoverflow.com/questions/2482916/what-am-i-missing-in-the-xmlhttprequest) –

+2

si está abierto a las bibliotecas JS, jQuery realmente simplifica esto con el método .load() : http://api.jquery.com/load/ – scunliffe

+8

gracias a Dios, finalmente un resultado de google que no aborda jQuery: | –

Respuesta

175

Puede obtenerlo por XMLHttpRequest.responseText en XMLHttpRequest.onreadystatechange cuando XMLHttpRequest.readyState es igual a XMLHttpRequest.DONE.

Aquí hay un ejemplo (no es compatible con IE6/7).

var xhr = new XMLHttpRequest(); 
xhr.onreadystatechange = function() { 
    if (xhr.readyState == XMLHttpRequest.DONE) { 
     alert(xhr.responseText); 
    } 
} 
xhr.open('GET', 'http://example.com', true); 
xhr.send(null); 

Para una mejor compatibilidad crossbrowser, no sólo con IE6/7, sino también para cubrir algunas fugas o fallos de memoria específicas del navegador, y también para disparar con menos verbosidad solicitudes ajaxical, podría utilizar jQuery.

$.get('http://example.com', function(responseText) { 
    alert(responseText); 
}); 

Tenga en cuenta que usted tiene que tomar la Same origin policy for JavaScript en cuenta cuando no esté funcionando a localhost. Es posible que desee considerar crear un script proxy en su dominio.

+0

¿Cómo hacemos para hacer ese proxy? –

10

En XMLHttpRequest, utilizando XMLHttpRequest.responseText puede plantear la excepción, como a continuación

Failed to read the \'responseText\' property from \'XMLHttpRequest\': 
The value is only accessible if the object\'s \'responseType\' is \'\' 
or \'text\' (was \'arraybuffer\') 

mejor manera de acceder a la respuesta de la siguiente manera XHR

function readBody(xhr) { 
    var data; 
    if (!xhr.responseType || xhr.responseType === "text") { 
     data = xhr.responseText; 
    } else if (xhr.responseType === "document") { 
     data = xhr.responseXML; 
    } else { 
     data = xhr.response; 
    } 
    return data; 
} 

var xhr = new XMLHttpRequest(); 
xhr.onreadystatechange = function() { 
    if (xhr.readyState == 4) { 
     console.log(readBody(xhr)); 
    } 
} 
xhr.open('GET', 'http://www.google.com', true); 
xhr.send(null); 
10

yo sugeriría mirar en fetch. Es el equivalente de ES5 y usa Promesas. Es mucho más legible y fácil de personalizar.

const url = "https://stackoverflow.com"; 
 
fetch(url) 
 
    .then(
 
     response => response.text() // .json(), etc. 
 
     // same as function(response) {return response.text();} 
 
    ).then(
 
     html => console.log(html) 
 
    );

Más información:

Mozilla Documentation

Can I Use (88% Mar 2018)

Matt Walsh Tutorial

Cuestiones relacionadas