在PhoneGap / Cordova中的Web-worker中允许使用XHR吗? [英] Is XHR allowed within web-worker in PhoneGap/Cordova?

查看:135
本文介绍了在PhoneGap / Cordova中的Web-worker中允许使用XHR吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

环境:Cordova 2.9.0,iOS(运行iOS 6.1.3的Xcode 4.6.3 iPad 6.1模拟器和iPad 3)

Environment: Cordova 2.9.0, iOS (Xcode 4.6.3 iPad 6.1 Simulator and iPad 3 running iOS 6.1.3)

我正在尝试将将另一个文件加载到网络工作者的处理。我正在加载的文件是应用程序的一部分(意味着它位于同一域中)。

I am trying to separate out the processing of loading another file into a web-worker. The file I am loading is part of the application (meaning it is in the same domain).

以下代码在未在网络工作者中运行时可以正常工作:( URL 的格式为 /db/file.json)

The following code works fine when NOT run in a web-worker: (url is of the form "/db/file.json")

function loadXMLDoc(url, successCallback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState==4 && (xmlhttp.status==200 || xmlhttp.status == 0)) {
        successCallback(xmlhttp.responseText);
    }
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}

注意:使用cordova时状态始终为0 。当不使用cordova时,状态为200。

NOTE: status is always 0 when using cordova. status is 200 when not using cordova.

当我将此代码分离为网络工作者时,responseText返回为空。

When I separate this code into a web-worker the responseText comes back empty.

我删除了phoneGap并验证了上面的代码在没有网络工作者的情况下都可以使用。

I removed phoneGap and verified that the code above worked with and without a web-worker.

是否可以使用XHR

推荐答案

中,您可能需要检查服务器是否正确支持跨源资源共享。有一些方便的资源,例如W3C的 CORS已启用

You will likely want to check that your server properly supports Cross Origin Resource Sharing. There are some handy resources for this, such as CORS Enabled, by the W3C.

在没有Cordova的情况下运行此程序,实际上可能是从服务器(例如 http://www.myserver)加载页面。 com / index.html ,但是当您从Cordova运行它时,实际上是在运行 file:///somesome//www/index.html 。这意味着,如果您尝试使用ajax请求从 myserver.com 访问信息,则该信息位于其他域中,并且如果未正确设置,浏览器将拒绝响应。

When you run this without Cordova, you're likely actually loading a page from a server, such as http://www.myserver.com/index.html, but when you run it from Cordova, you're actually running file:///somedirectory/www/index.html. This means that if you attempt to use an ajax request to access information from myserver.com, it is on a different domain, and if not properly set up, the browser will reject the response.

您可以做的最重要的事情是启用跨域资源共享。这需要添加一个新的标头 Access-Control-Allow-Origin ,其值为 *

The most important thing you can do is enable Cross-Origin Resource Sharing. This requires adding a new header Access-Control-Allow-Origin who's value is *

这篇关于在PhoneGap / Cordova中的Web-worker中允许使用XHR吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆