问题
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).
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();
}
NOTE: status is always 0 when using cordova. status is 200 when not using cordova.
When I separate this code into a web-worker the responseText comes back empty.
I removed phoneGap and verified that the code above worked with and without a web-worker.
Is it possible to use XHR in a web-worker within phoneGap/cordova?
回答1:
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.
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.
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 *
回答2:
For this case you can solve it by change the way to load the file.
- Forget XMLHttpRequest, because do not work with
file://
protocol. - Change the extension of the file from .json to .js
- Set you JSON object into a variable. Ej.
var myJson = { "a":123,"b":789 };
- Load your JS file into your HTML.
<script src="db/file.json"></script>
- Read you data in JavaScript. Ej.
console.log(myJson);
回答3:
Yes XHR does work for local files with cordova version 6.0.0 (cordova-ios version 3.x) in workers with the default iOS 9.2 UIWebView and (oddly) XMLHttpRequests work for the file:
protocol (unlike pretty much all other browsers). While I assume this is true across all the cordova implementations I haven't yet tried them all myself. As mentioned the status = 0
but both load
and error
handlers fire and responseType
affects the response
(xhr2) all as-expected. Unfortunately all of the File System APIs are not accessible so this makes for a peculiar/hacky way to access local files (related bug).
note: experimenting with update to cordova-ios version to 4.0 and WKWebView version 1.0.2-dev (still cordova version 6.0) and file:
urls no longer work.
来源:https://stackoverflow.com/questions/17496239/is-xhr-allowed-within-web-worker-in-phonegap-cordova