javascript - 如何从函数返回 XMLHttpRequest 响应?

标签 javascript networking xmlhttprequest react-native

<分区>

值未被替换且函数返回 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;
}

最佳答案

你不能那样返回值。

我建议使用回调或 promise :

回调:

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

promise :

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

关于javascript - 如何从函数返回 XMLHttpRequest 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38829610/

相关文章:

javascript - 按高度百分比填充最后一个在象形图中绘制的 svg 图形(d3.js)

javascript - 如何让 KendoUI Validator 忽略隐藏的表单元素?

java - 使用 VirtualBox 在虚拟机上测试客户端/服务器 Java 应用程序

javascript - 跨源请求被阻止 - 如何在无法访问服务器的情况下绕过它

javascript - 如何使用一个依赖于另一个的 2 个 XMLHttpRequest?

javascript - 数据绑定(bind) attr mailto、主题和正文

javascript - 无法使用 asp.net 调用函数(窗口){}

c++ - 识别进程正在某些端口 C/C++ Windows 中运行

java - UDP 将数据从一台设备发送到另一台设备

jquery - AJAX 使用 CORS 获取自定义响应 header