2011-02-08 56 views
0

我想尝试一些非常简单的我的第一个Firefox附加组件,重要的部分是:Firefox扩展:使用XMLHttpRequest的多个请求。使用异步还是不?

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

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

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

基于我的实施multiple 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(){}; 
    } 
    } 

回答

3

你应该总是避免做同步的网络请求,因为它会从运行阻止GUI,直到你一个回应。仅仅因为网络对你来说可能很快,你不应该认为它对于所有的用户来说都是快速的。

+0

好。我明白那个。现在,你会像我这样编码吗?我最感兴趣的是从alertContents()调用doRequest() – AntonioHerraizS 2011-02-08 22:50:48