【问题标题】:How I can return XMLHttpRequest response from function? [duplicate]如何从函数返回 XMLHttpRequest 响应? [复制]
【发布时间】:2016-12-14 06:03:39
【问题描述】:

值不是替换,函数返回 0。如何解决? (react-native 0.30, IOS 10.0 模拟器)

export function getCategoryList() {
  var xhr = new XMLHttpRequest();
  jsonResponse = null;

  xhr.onreadystatechange = (e) => {
    if (xhr.readyState !== 4) {
      return;
    }

    if (xhr.status === 200) {
      console.log('SUCCESS', xhr.responseText);
      jsonResponse = JSON.parse(xhr.responseText);
    } else {
      console.warn('request_error');
    }
  };

  xhr.open('GET', 'https://httpbin.org/user-agent');
  xhr.send();

  return jsonResponse;
}

【问题讨论】:

  • 请求是异步的,这意味着请求被发送,你的函数返回一个空值,然后一段时间后请求完成。看看将回调函数传递给getCategoryList()(简单)或promise(有点困难,但不多)。
  • 你应该寻找promise

标签: javascript networking xmlhttprequest react-native


【解决方案1】:

你不能这样返回值。

我建议使用回调或承诺:

回调:

function getCategoryList(callback) {
  var xhr = new XMLHttpRequest();

  xhr.onreadystatechange = (e) => {
    if (xhr.readyState !== 4) {
      return;
    }

    if (xhr.status === 200) {
      console.log('SUCCESS', xhr.responseText);
      callback(JSON.parse(xhr.responseText));
    } else {
      console.warn('request_error');
    }
  };

  xhr.open('GET', 'https://httpbin.org/user-agent');
  xhr.send();
}

getCategoryList(data => console.log("The data is:", data));

承诺:

function getCategoryList() {
  var xhr = new XMLHttpRequest();

  return new Promise((resolve, reject) => {

    xhr.onreadystatechange = (e) => {
      if (xhr.readyState !== 4) {
        return;
      }

      if (xhr.status === 200) {
        console.log('SUCCESS', xhr.responseText);
        resolve(JSON.parse(xhr.responseText));
      } else {
        console.warn('request_error');
      }
    };

    xhr.open('GET', 'https://httpbin.org/user-agent');
    xhr.send();
  });
}

getCategoryList().then(res => console.log("The result is", res));

【讨论】:

  • 那么对于 AJAX,这意味着没有办法使用像 getCategoryList() 这样的简单函数调用来返回数据?这样会方便很多。更新:看起来最接近的解决方案是使用 async / await 但是你仍然不能直接调用函数,你必须在函数名之前使用 await 关键字调用它(即使你嵌套了 await 函数调用在另一个函数中,调用另一个函数也需要等待):stackoverflow.com/questions/48969495/…
【解决方案2】:

如果 XHR 是同步的 (xhr.open('GET', 'https://httpbin.org/user-agent', false)),您可以返回请求响应,执行一个无限循环,在请求完成时中断。

注意事项:

  • 不推荐使用同步 XHR;
  • 无限循环将在 XHR 未完成时停止页面(例如,游戏)。

function getCategoryList() {

    var xhr = new XMLHttpRequest();
    xhr.open("GET", "https://httpbin.org/user-agent", false);
    xhr.send();

    // stop the engine while xhr isn't done
    for(; xhr.readyState !== 4;)

    if (xhr.status === 200) {

        console.log('SUCCESS', xhr.responseText);

    } else console.warn('request_error');

    return JSON.parse(xhr.responseText);
}

【讨论】:

  • 不支持同步http请求
  • @iwasmusic 它们是,但已弃用,然后它们将在未来被删除。这就是您想要的(“我怎样才能从...返回 XMLHttpRequest 响应”)。
猜你喜欢
  • 2023-04-02
  • 2019-10-28
  • 2015-06-18
  • 2018-08-24
  • 2012-03-23
  • 2017-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多