Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/418.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript XMLHttpRequest和Web工作者访问控制源_Javascript_Html_Xmlhttprequest_Web Worker - Fatal编程技术网

Javascript XMLHttpRequest和Web工作者访问控制源

Javascript XMLHttpRequest和Web工作者访问控制源,javascript,html,xmlhttprequest,web-worker,Javascript,Html,Xmlhttprequest,Web Worker,在使用webworkers进行XMLHttpRequest时,我正在处理一些访问控制源问题 该问题在以下代码main.js中很容易重现: var worker = new Worker('js/createSimplePage.js'); worker.onmessage = function () { console.log('message recieved'); }; 和js/createSimplePage.js: var xmlhttp = new XMLHttpRequest(

在使用webworkers进行XMLHttpRequest时,我正在处理一些访问控制源问题

该问题在以下代码main.js中很容易重现:

var worker = new Worker('js/createSimplePage.js');
worker.onmessage = function () {
  console.log('message recieved');
};
和js/createSimplePage.js:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
  if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
    console.log(xmlhttp.responseText);
  }
};
xmlhttp.open("GET", "http://search.twitter.com/search.json?q=balling&rpp=20&callback=", true);
xmlhttp.setRequestHeader('Content-Type', 'text/plain');
xmlhttp.send();
如果我在index.html的标题中包含createSimplePage.js,它运行良好,并从twitter API打印正确的响应。但是,如果我只加载main.js并让它尝试以web worker的身份加载createSimplePage.js,那么我会收到错误:

XMLHttpRequest cannot load http://search.twitter.com/search.json?q=balling&rpp=20&callback=. 
Origin file:// is not allowed by Access-Control-Allow-Origin.
在SimpleHTTPServer上托管文件时也会发生类似的错误,但错误如下:

 "Origin http://127.0.0.1:8000 is not allowed by Access-Countrol-Allow-Origin."

我不明白为什么作为web工作者加载它会破坏它,使它无法访问API。

我认为web工作者的安全级别与浏览器不同。也许您可以确保返回的脚本带有allow all Originates标头:

header("Access-Control-Allow-Origin: *");
最好删除自定义标题:

xmlhttp.setRequestHeader('Content-Type', 'text/plain');
本网站提供了更多信息: