i'm a bit new to JQuery and ajax, so i apologize if this is a newbie's question.
I'm trying to use ajax from a local file to access the web (for example, getting a text file).
I'm not using IIS or anything, simple file from my hard drive (and i need it to stay that way).
Checked it on both IE8 and Chrome (version 11.0.696.60).
Here's some javascript to illustrate:
// use ajax to load from the web
$("#webText").click(function(){
$.get("http://www.w3schools.com/jquery/demo_ajax_load.txt", function(result){
alert(result);
});
This code is trying to load a text file from the web - the operation fails on both IE and chrome (won't get to get to the success function).
Chrome's notifies in the error console about "XmlHttpRequest cannot load _http://www.w3schools.com/jquery/demo_ajax_load.txt: Origin null is not allowed by Access-Control-Allow-Origin"
// use ajax to load from a local file
$("#localText").click(function(){
$.get("demo_ajax_load.txt", function(result){
alert(result);
});
This code is trying to load from a local text file.
IE: the operation succeeds.
Chrome: fails with same error as above.
At this point i thought it was impossible to communicate with the web from a local file, but then i came across a similar question: XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin
Using the examples given there, I tried:
// use ajax to load json object from the web
$("#webJSON").click(function(){
var url = 'http://www.panoramio.com/wapi/data/get_photos?v=1&key=dummykey&tag=test&offset=0&length=20&minx=-30&miny=0&maxx=0&maxy=150';
$.get(url, function(json) {
alert(json.photos[1].photoUrl);
}, "jsonp");
});
And this code works great on both browsers. So obviously, it is possible to communicate with a web service from a local file.
Any ideas?
BTW - i'm more interested with the IE aspect of this, Chrome and other browsers are less of an issue.
Thanks.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…