尝试从web-worker获取base64中的图像。一切都很好,除了工人多次回复.onmessage
事件:
main.js部分:
var worker = new Worker( 'js/ww.js' );
worker.onmessage = function(e) {
console.log( e );
};
worker.postMessage( { url: '/api/aerial?x=159&y=94&zoom=8&base64=true' } );
ww.js,WebWorker部分:
var self = this;
function makeRequest( url ) {
var httpRequest = new XMLHttpRequest();
if ( !httpRequest ) {
console.error( 'Giving up. Cannot create an XMLHTTP instance.' );
return false;
}
httpRequest.onreadystatechange = function() {
var response = httpRequest.responseText;
self.onMessage = postMessage( response );
};
httpRequest.open( 'GET', url, true );
httpRequest.send();
}
self.addEventListener( 'message', function( event ) {
makeRequest( event.data.url );
});
为什么会多次开火?
可能是因为使用了这种原生AJAX吗?
答案 0 :(得分:0)
检查请求的正确状态和状态
在onreadystatechange
- 处理程序中,您应该执行以下操作:
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState == 4 && httpRequest.status == 200) {
var response = httpRequest.responseText;
self.onMessage = postMessage( response );
}
}