存储xmlhttp响应以供进一步使用

时间:2018-02-20 10:57:20

标签: javascript reactjs xmlhttprequest

我制作了React App。我在同一个组件中有2 xmlhttprequest个。我尝试将responseTextxhr1存储到一些随机新变量中,以便我可以将其显示或作为xhr2中的数据发送。如何将xhr1.responseText的内容存储为var resp?它不是ajax而我没有使用onreadystatechange功能。对不起,如果我的问题是错的,但我还是新手。感谢。



var xhr1 = new XMLHttpRequest();
xhr1.open('POST', 'http://myserver/login');
xhr1.setRequestHeader("Content-Type", "application/json");
xhr1.onload = function() {
  console.log('Refresh Key : ' + xhr1.responseText);
};
xhr1.send(JSON.stringify({
  "idToken": id_token,
  "fcmID": ""
}));

var xhr2 = new XMLHttpRequest();
xhr2.open('POST', 'http://myserver/getAccessToken');
xhr2.setRequestHeader("Content-Type", "application/json");
xhr2.onload = function() {
  console.log('Access Token : ' + xhr2.responseText);
};
//The following line doesn't work as expected. 
xhr2.send(JSON.stringify({
  "refreshToken": xhr1.responseText
}))

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
&#13;
&#13;
&#13;

有什么方法可以让代码的最后一行有效吗?

1 个答案:

答案 0 :(得分:0)

问题是因为它是异步的。这意味着发送请求(或者更确切地说是接收响应)将从正常执行流程中取出。

解决方案:要解决此问题,您可以重新构建代码并使用回调,如下所示:

回调只是传递给另一个函数的函数。其他函数可以在函数准备就绪时调用函数。在异步进程的上下文中,只要异步进程(xhr1请求)完成,就会调用回调。通常,结果(xhr1响应)将传递给回调。

在您的代码中,您可以使handleData接受回调并将其用作成功回调。 希望它能解决你的问题。

 function handleData(callback) {

  var xhr1 = new XMLHttpRequest();
  xhr1.open('POST', 'http://myserver/login');
  xhr1.setRequestHeader("Content-Type", "application/json");
  xhr1.onload = function() {  // when the xhr1 request is loaded
  console.log('Refresh Key : ' + xhr1.responseText);
  callback(xhr1.responseText); // xh1 response sent via callback

    };

   xhr1.send(JSON.stringify({
  "idToken": id_token,
  "fcmID": ""
    }));

  }


  handleData(function (result) {
   // code that depends on result of Xhr1 request
   var xhr2 = new XMLHttpRequest();
   xhr2.open('POST', 'http://myserver/getAccessToken');
   xhr2.setRequestHeader("Content-Type", "application/json");
   xhr2.onload = function() {
   console.log('Access Token : ' + xhr2.responseText);
     };

   xhr2.send(JSON.stringify({
   "refreshToken": result // result is xh1 response received via callback
    }))

});

handleData 函数现在接受AJAX成功完成时要运行的操作。 您还可以通过检查响应状态是否为200(i,创建失败处理程序)进一步扩展xhr1.onload = function(),然后相应地执行操作。