使用JSONP和Web Workers的跨源资源共享(CORS)

时间:2010-09-01 08:59:41

标签: jsonp web-worker cors

我正在寻找解决方案如何使用Web Workers中的JSONP从/向另一个域发送/发送数据。

由于Web Workers无法访问DOM,因此无法将带有url和callback参数的<script>标记附加到Web Workers的<head>标记中。

有人知道,如何使用JSONP和Web Workers从/向另一个域获取/发布数据?

谢谢,

2 个答案:

答案 0 :(得分:4)

CORS是一个与JSONP无关的规范,除了在新的浏览器中过时之外。它使用普通的XMLHttpRequest调用启用跨域请求。

这是an overview它的工作原理以及如何使用它。它可以在Firefox 3.5 +,Safari 4 +,Chrome 3 +,Internet Explorer 8+和anything else using one of the same engines中使用。

答案 1 :(得分:2)

看一下这段代码:

// Helper function to make the server requests 
function MakeServerRequest() 
{
    importScripts("http://SomeServer.com?jsonp=HandleRequest");
} 

// Callback function for the JSONP result 
function HandleRequest(objJSON) 
{
    // Up to you what you do with the data received. In this case I pass 
    // it back to the UI layer so that an alert can be displayed to prove 
    // to me that the JSONP request worked. 
    postMessage("Data returned from the server...FirstName: " 
                  + objJSON.FirstName + " LastName: " + objJSON.LastName);
} 

// Trigger the server request for the JSONP data 
MakeServerRequest();
相关问题