Web Workers和JSON

时间:2014-08-04 22:14:22

标签: javascript json html5 web-worker

我确信这段代码中缺少一些东西,我无法弄清楚它是什么。

这是主页:

  <script>
    function wwCallback(e) {
        document.write(e.data);
    }
    function wwError(e) {
        alert(e.data)
    }
    $(document).ready(function () {
        var worker = new Worker("sync.js");
        worker.onmessage = wwCallback;
        worker.onerror = wwError;
        worker.postMessage({
            'cmd': 'downloadUser',
            'url': 'server.php'
        });
        console.log("WW Started");
    });
</script>

Server.php只是回显一个JSON字符串,我已经验证它是有效的并且使用正常的ajax请求工作。

这是我的网络工作者代码:

function getData(url) {
var req = new XMLHttpRequest();

//expect json
    req.open('GET', url);
    req.send(null);
    req.onreadystatechange = function () {
        if (req.readyState == 4) {
            if (req.status == 200) {
                self.postMessage(req.responseText);
            }
        }
    }
} 

self.addEventListener('message', function (e) {
  var data = e.data;
  switch (data.cmd) {
    case 'downloadUser':
        getData(data.url);
   }
    self.close();
}, false);

有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:0)

您的问题出在您的WebWorker XHR调用中。您已打开请求,然后在您设置事件处理程序以处理响应之前立即发送请求。您只需要在设置事件处理程序的代码下面移动req.send(null);调用。

试试这个:

function getData(url) {
var req = new XMLHttpRequest();

//expect json
    req.open('GET', url);
    //  req.send(null);        // remove this line from here.
    req.onreadystatechange = function () {
        if (req.readyState == 4) {
            if (req.status == 200) {
                self.postMessage(req.responseText);
            }
        }
    }
    req.send(null);        // make the request after your readystatechange
                           // handler is set up.
} 

self.addEventListener('message', function (e) {
  var data = e.data;
  switch (data.cmd) {
    case 'downloadUser':
        getData(data.url);
   }
    self.close();
}, false);