Web Workers and JSON
Web Workers and JSON
我确信有一些东西是我从这段代码中缺失的,我只是无法弄清楚它是什么。
主页面:
<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请求工作。
这是我的web workers代码:
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);
谁能给我指个正确的方向? 你的问题是在你的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);
相关文章:
- Ajax and Json with Rails
- JSON and jQuery Search
- JSON and javascript objects
- Remote json and Javascript
- JSON and javascript
- JSON and AJAX response
- JSON and Highcharts
- JSON and Angularjs
- Pupulate Dom HTML fom JSON and coffeescript
- JSON and AJAX with Python
- Securing JSON and ASP.NET MVC2
- Working with JSON and Angular NVD3
- json and null values
- Parsererror with json and PHP
- RIA Services JSON and Ext.Js
- JSON and Python
- Laravel 3 JSON and jQuery getJSON
- json and javascript issue
- JSON and Angular
- flickr api, json and set list