script-lab
script-lab copied to clipboard
XMLHttpRequest do not work
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" }
Any update on this one?
Always use $.ajax, or fetch API to do those kind of request.
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);
}