xmlhttprequest特殊发送

xmlhttprequest special send

我想就 xmlhttprequest 寻求您的帮助。我想执行发送 xmlhttp 请求以仅在收到上一个 http 响应时重复从服务器获取图片。

在服务器端,我创建了带有 xmlhttp 状态标记的 http 响应 =900.So 我想在收到由于先前请求引起的响应后发送请求,否则,程序应该等到它到达.

例如:

当我在浏览器某处按下按钮时,它会触发对服务器的第一张图片 (jpeg) 请求,然后等待服务器的响应。得到状态为900的Http响应后,xmlhttp会解码响应并将图片显示在(image)上。

在下面的代码中,通过使用 wireshark 捕获数据包,我想我成功地获得了正确的数据包流。但是,图片无法在 DIV.

中显示

谁能帮帮我?非常感谢!

    enter code here
      function init(url)
      {
      var xmlHTTP = new XMLHttpRequest();    
      xmlHTTP.open('GET',url,true);
      xmlHTTP.send();
      xmlHTTP.responseType = 'arraybuffer';
       xmlHTTP.onload = function(e)
      {
        var arr = new Uint8Array(this.response);
       var raw = String.fromCharCode.apply(null,arr);
       var b64=btoa(raw);
       var dataURL="data:image/jpeg;base64,"+b64;
       document.getElementById("image").src = dataURL;
       };
      xmlHTTP.onreadystatechange=function(){
      buff(xmlHTTP.status);

       }
       }
      buff(status){
      if (status=900){
        sleep(1000);
      init('/images/photos/badger.jpg');
       }
         }
        function sleep(milliseconds) {
              var start = new Date().getTime();
              for (var i = 0; i < 1e7; i++) {
                if ((new Date().getTime() - start) > milliseconds){
                    break;
                }
              }
          }            
        </script>
         </head>
         <body>
         <div id="image"><h2>picture display here</h2></div>
          <button type="button" onclick=buff(900)>Get Picture</button>

在此处输入代码

您的代码有几个问题。

标记

您的标记存在问题,您正在使用 div 标签来显示图像。 div 标签不支持 src 属性。您应该使用 img 标签,而不是像这样:

....
<img id="image" />
<button type="button" onclick="buff(900)">Get Picture</button>

状态码

您为什么使用状态 900?如果请求正确并且图像已加载,请使用状态 200。

图片加载

为什么还要使用 XMLHttpRequest 来加载图像? 您只需更改 img 标签上的 src 属性,浏览器就会请求图像。

如果您想重新加载图像,您可以刷新 src 属性。如果所有图片都在同一个 URL 下投放,您可以添加请求参数,例如当前时间:

document.getElementById("image").src = "/images/photos/badger.jpg#" + new Date().getTime();

这样浏览器将再次请求图像,而不会使用已经加载和缓存的图像。有关详细信息,请参阅 this answer。 (其实问题和你的差不多。。。)

休眠功能

您的睡眠函数将使用资源,因为它是一个在指定时间内不断 运行 的循环。虽然它 运行s,但它会添加数字并进行完全不必要的比较。 请使用 setTimeout():

中的 javascript 之类的东西
buff(status) {
  if(status === 900) {
    setTimeout(funciton(){
      init('/images/photos/badger.jpg');
    }, 1000);
  }
}

更新:工作示例

我在代码片段中设置了一个工作示例。它从同一个 url 加载图像,但它们是由 lorempixel 在每次请求时随机提供的。

我重新组织了图像加载。其实还有一个问题。您使用 onreadystatechange 开始加载下一张图片。这将在 readystate 的每次更改时触发,而不仅仅是在加载图像时触发。因此我从 onload() 开始下一个 buff() 像这样:

var xmlHTTP = new XMLHttpRequest();    
xmlHTTP.open('GET',url,true);

xmlHTTP.responseType = 'arraybuffer';
xmlHTTP.onload = function(e) {
    var arr = new Uint8Array(this.response);
    var raw = String.fromCharCode.apply(null,arr);
    var b64 = btoa(raw);
    var dataURL = "data:image/jpeg;base64," + b64;
    document.getElementById("image").src = dataURL;
    buff(this.status);
};
xmlHTTP.send();

为了方便起见,我添加了一个停止加载新图像的按钮。 对于您的示例,您只需更改 imageUrl 和 imageStatus 变量。

var imageUrl = "http://lorempixel.com/400/200/", // set to "/images/photos/badger.jpg" for your example
    imageStatus = 200, // set to 900 for your example
    stopped = true;

function stopLoading() {
    stopped = true;
}

function loadNextImage(url) {
    if(!stopped) { // only load images if loading was not stopped
        var xmlHTTP = new XMLHttpRequest();    
        xmlHTTP.open('GET',url,true);
        
        xmlHTTP.responseType = 'arraybuffer';
        xmlHTTP.onload = function(e) {
            var arr = new Uint8Array(this.response);
            var raw = String.fromCharCode.apply(null,arr);
            var b64 = btoa(raw);
            var dataURL = "data:image/jpeg;base64," + b64;
            document.getElementById("image").src = dataURL;
            buff(this.status); // set the next timer when the current image was loaded.
        };
        xmlHTTP.send();
    }
}

function buff(status) {
    if (status === imageStatus) {
        setTimeout(function() {
            loadNextImage(imageUrl + "?" + new Date().getTime());
        }, 1000);
    } else { 
        // Status does not match with expected status. 
        // Therefore stop loading of further images
        stopLoading();
    }
}

function init() {
    stopped = false;
    loadNextImage(imageUrl);
}


document.getElementById("start").onclick = function(){
    init(imageUrl);
};
document.getElementById("stop").onclick = stopLoading;
<img id="image" />
<button type="button" id="start">Get pictures</button>
<button type="button" id="stop">No more pictures</button>