JavaScript函数onload从未调用

时间:2019-04-09 18:58:23

标签: javascript xmlhttprequest

我希望从Web服务获取带有get请求的json文件,并且我有一个“跨源请求”,所以我选中“ withCredentials”,然后使用onload函数在上显示json的内容。控制台。

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函数从未被调用过,并且我没有任何错误。我确定Web服务正在运行,因为我在浏览器中尝试了它。您知道为什么从不调用onload函数吗?

EDIT:显示console.log("withCredentials is true");,但不显示console.log('ok');

1 个答案:

答案 0 :(得分:1)

您需要

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