How to get the response of XMLHttpRequest?

后端 未结 4 1628
挽巷
挽巷 2020-11-22 06:23

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 l

4条回答
  •  太阳男子
    2020-11-22 07:17

    I'd suggest looking into fetch. It is the ES5 equivalent and uses Promises. It is much more readable and easily customizable.

    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)
        );

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

    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:

    Mozilla Documentation

    Can I Use (94% Oct 2019)

    Matt Walsh Tutorial

提交回复
热议问题