Firefox Extension - Multiple XMLHttpRequest calls per page

前端 未结 2 1064
生来不讨喜
生来不讨喜 2021-02-11 08:35

I am trying to create a Firefox extension that can run multiple XMLHttpRequests per page. The code is below (my main function calls the makeRequest on different URLs). My proble

2条回答
  •  庸人自扰
    2021-02-11 08:56

    Your problem is you've only got one http_request identifier which is reused every time the makeRequest function is called. Here is one simple adjustment:-

    function makeRequest(url,parameters) {
       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 + parameters, true);
       http_request.send(null);
           return http_request;
    }
    
    function alertContents(http_request) {
       if (http_request.readyState == 4) {
          if (http_request.status == 200) {
                alert('Found: ' + http_request.responseText);
          } else {
             alert('There was a problem with the request.');
          }
                  http_request.onreadystatechange = fnNull;
       }
    }
    
        function fnNull() { };
    

    The http_request identifier is local to each makeRequest execution. The correct instance of XHR is then passed to alerrContents each time onreadystatechange is fired by using a capture.

    BTW, why separate url from parameters? Since the caller has to ensure the parameters argument is correctly url encoded it doesn't seem like a very useful abstraction. In addition the caller can simply pass a URL containing a querystring anyway.

提交回复
热议问题