繁体   English   中英

Firefox扩展:使用XMLHttpRequest的多个请求。 是否使用异步?

[英]Firefox Extension: multiple requests with XMLHttpRequest. Use Asynchronous or not?

对于第一个Firefox插件,我正在尝试一些非常简单的方法,重要的部分是:

步骤1)调用外部API来检索一些数据。
第2步)使用首次获取的数据再次调用该API,以获取更多信息。

现在,我首先使用XMLHttpRequest在同步模式下实现了它,因为我认为需要等待步骤2迫使我这样做。 对处理该API调用的函数的两次调用使用XMLHttpRequest并解析了响应。 精细。

然后我遇到了Mozilla开发网络中的各种文档,这些文档鼓励您在异步模式下使用XMLHttpRequest,因此我尝试了。

将我的实现基于多个XMLHttpRequests和其他对象,我想到了以下代码。

我的问题是:这是正确的方法吗? 我应该回到使用同步模式吗? 它的工作原理是这样的,但是它并没有让我成为您将要使用的正确AJAX模式...

  // first call
  var username = foo;
  var password = bar;
  var startOffset = 0; // initial value
  var url = encodeURIComponent('https://theapiurl.com/query=' + startOffset);
  doRequest();

  function doRequest() {
    makeRequest(url, username, password);
  }

  function makeRequest(url, username, password) {
    var http_request = new XMLHttpRequest();
    if (http_request.overrideMimeType) {
      http_request.overrideMimeType('text/xml');
    }
    if (!http_request) {
      alert('Cannot create XMLHTTP instance');
      return false;
    }
    http_request.onreadystatechange = function() { 
       alertContents(http_request);
    };
    http_request.open('GET', url, true, username, password);
    http_request.send(null);
  }  

  function alertContents(http_request) {
    if (http_request.readyState == 4) {
      if (http_request.status == 200) {
        if (startOffset == 0) {
          startOffset = 45; // this value would be extracted from 'http_request'
          url = encodeURIComponent('https://theapiurl.com/query=' + startOffset);
          // second call, parameter startOffset has changed
          doRequest();
        } else {
        }
      } else {
        alert('There was a problem with the request.');
      }
      http_request.onreadystatechange = function fnNull(){};
    }
  }

您应该始终避免执行同步网络请求,因为这将阻止GUI起作用,直到获得响应为止。 仅仅因为网络对您来说是快速的,您不应该假设它对所有用户都是快速的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM