1

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

由于 Web Worker 无法访问 DOM,因此无法将<script>带有 url 和回调参数的<head>标签附加到来自 Web Worker 的标签上。

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

谢谢,

4

2 回答 2

4

CORS 是一种规范,它与 JSONP 无关,只是在较新的浏览器中使其过时。它使用普通的 XMLHttpRequest 调用启用跨域请求。

以下是它如何工作以及如何使用它的概述。它可以在 Firefox 3.5+、Safari 4+、Chrome 3+、Internet Explorer 8+ 以及使用相同引擎之一的任何其他设备中使用。

于 2010-09-19T05:16:33.313 回答
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();
于 2011-12-09T05:41:45.703 回答