script-lab icon indicating copy to clipboard operation
script-lab copied to clipboard

XMLHttpRequest do not work

Open Pher0ah opened this issue 4 years ago • 2 comments

Hi, I have tried to use XMLHttpRequest to get information but it seems this always errors out; I do not get any error message or output that I can share, but a simple function below shows that this is not working...

const strURL = "https://www.google.com/" var xmlHttp = new XMLHttpRequest(); xmlHttp.open('GET', strURL, false); // false for synchronous request xmlHttp.send(null); var ret = xmlHttp.responseText; console.log(xmlHttp);

The console output is...

{ "readyState": 0, "status": 0, "statusText": "error" }

Pher0ah avatar Jun 03 '21 23:06 Pher0ah

Any update on this one?

mattehalen avatar Mar 27 '22 20:03 mattehalen

Always use $.ajax, or fetch API to do those kind of request.

chenxizhang avatar Sep 04 '22 14:09 chenxizhang

This is a great question for Stack Overflow.

The code below shows how to use fetch and XMLHttpRequest and both are working for me.

async function test() {
    const url =
    "https://gist.githubusercontent.com/wandyezj/e8720b3b12022f7247ba4ee76aca170f/raw/6cea1f760438936a3ef17b572fd81c29d1dc7833/script-lab-import-example-excel.yaml";
  
  const request = await fetch(url);
  const text = await request.text();
  console.log("fetch", text.slice(0, 20).replaceAll("\n", " "));

  const xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onload = (e) => {
  if (xhr.readyState === 4) {
    if (xhr.status === 200) {
      console.log("xml response", xhr.responseText.slice(0, 20).replaceAll("\n", " "));
    } else {
      console.error(xhr.statusText);
    }
  }
};
xhr.onerror = (e) => {
  console.error(xhr.statusText);
};
xhr.send(null);
}

wandyezj avatar Apr 09 '24 21:04 wandyezj