从未调用过 Javascript 函数 onload [英] Javascript function onload never called
问题描述
我希望得到一个带有来自 webservice 的 get 请求的 json 文件,并且我有一个跨域请求",所以我选中了withCredentials",然后我使用 onload 函数将 json 的内容显示在控制台.
I wish to get a json file with a get request from a webservice, and I have a "cross origin request", so I check "withCredentials", and then I use the onload function to display the content of the json on the console.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
console.log("withCredentials is true");
xhr.onload = function() {
console.log('ok');
if (xhr.status >= 200 && xhr.status < 400) {
data.forEach(card => {
console.log(card.nameEnglish1);
})
} else {
console.log('error');
}
};
xhr.onerror = function() {
console.log('There was an error!');
};
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
var xhr = createCORSRequest('GET', 'http://192.168.42.176:8080/batch-recup-mtg-0.0.1-SNAPSHOT/mtg/cards/search?setCode=AKH');
if (!xhr) {
throw new Error('CORS not supported');
}
但是什么也没发生,我的 onload 函数从来没有被调用过,我也没有任何错误.我确定网络服务正在运行,因为我在浏览器中尝试过.您知道为什么从不调用 onload 函数吗?
But nothing happen, my onload function is never called, and I don't have any error. I'm sure that the webservice is working because I tried it in my browser. Do you have any idea why the onload function is never called?
EDIT : console.log("withCredentials is true");
显示,但 console.log('ok');
不是
EDIT : console.log("withCredentials is true");
is displayed, but console.log('ok');
isn't
推荐答案
您需要
xhr.send();
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
console.log("withCredentials is true");
xhr.onload = function() {
console.log('ok');
if (xhr.status >= 200 && xhr.status < 400) {
data.forEach(card => {
console.log(card.nameEnglish1);
})
} else {
console.log('error');
}
};
xhr.onerror = function() {
console.log('There was an error!');
};
// added send call here:
xhr.send();
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
var xhr = createCORSRequest('GET', 'http://google.com/');
if (!xhr) {
throw new Error('CORS not supported');
}
这篇关于从未调用过 Javascript 函数 onload的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!