How to get the response of XMLHttpRequest?

2022-08-30 00:52:17

I'd like to know how to use XMLHttpRequest to load the content of a remote URL and have the HTML of the accessed site stored in a JS variable.

Say, if I wanted to load and alert() the HTML of http://foo.com/bar.php, how would I do that?


答案 1

You can get it by XMLHttpRequest.responseText in XMLHttpRequest.onreadystatechange when equals to .XMLHttpRequest.readyStateXMLHttpRequest.DONE

Here's an example (not compatible with 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);

For better crossbrowser compatibility, not only with IE6/7, but also to cover some browser-specific memory leaks or bugs, and also for less verbosity with firing ajaxical requests, you could use jQuery.

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

Note that you've to take the Same origin policy for JavaScript into account when not running at localhost. You may want to consider to create a proxy script at your domain.


答案 2

Use !fetch

It is much more readable and easily customizable. All modern browsers and Node support it. Here is a more in depth tutorial

const url = "https://stackoverflow.com";
fetch(url)
  .then(
    response => response.text() // .json(), .blob(), etc.
  ).then(
    text => console.log(text) // Handle here
  );

You can optionally pass a second param, depending on the needs/type of request.

// Example request options
fetch(url, {
  method: 'post', // Default is 'get'
  body: JSON.stringify(dataToPost),
  mode: 'cors',
  headers: new Headers({
    'Content-Type': 'application/json'
  })
})
.then(response => response.json())
.then(json => console.log('Response', json))

In Node.js, you'll need to import using:fetch

const fetch = require("node-fetch");

If you want to use it synchronously (doesn't work in top scope):

const json = await fetch(url)
  .then(response => response.json())
  .catch((e) => {});

More Info:

Matt Walsh Tutorial

Mozilla Documentation

Can I Use