views:

95

answers:

3

Hello.

I want to use JavaScript to make a simple http get. I used jQuery to perform my request. My code runs on IE8.0 but not in Chrome (ver 6.0). My page has the following code: (to simplify, i made a simple request to a html page, but my needs is other)

 <!DOCTYPE html PUBLIC "-//IETF//DTD HTML 2.0//EN"> 
   <html> 
       <script type"text/javascript"    src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt; 
    <SCRIPT TYPE="text/javascript"  >

    function sendGet(){
        $.get(
            "http://www.google.pt",
            function(data) {
               alert('page content: ' + data);
        });
    }
    </SCRIPT>
    <head> 
        <title> Http Get Demonstration </title> 
    </head> 
    <body> 
        <p/>
        <input type="button" value="Http Get" onclick="sendGet();" />   
    </body> 
   </html> 

As i said, when i load this page on IE and press the button, i get the alert with the html code. But in Chrome the alert appears with empty text (null?). In Chrome Console from "Developer tools" i get the message: "XMLHttpRequest cannot load http://www.google.pt/. Origin null is not allowed by Access-Control-Allow-Origin."

Anyone can explain me what's the meaning of this message? And what i should change to my page run in Chrome?

Thanks

+8  A: 

Due to same origin policy you cannot send AJAX requests to different domains than the one hosting your page. So unless your page is hosted on http://google.pt you cannot send an AJAX request to this domain. One possible workaround is to setup a server side script on your domain which will act as bridge between google.pt and the client or use JSONP if the distant domain supports it.

Darin Dimitrov
Why does it work on IE then?
Júlio Santos
I think (but I am not sure about it) that you can override the security policy in your IE settings to allow cross domain requests. This is not the default settings though that most users have and definitely not something you can rely on. The exact same code failed when I ran it on my IE8 with default settings. I've put a [jsfiddle test](http://www.jsfiddle.net/nMsCE/). Chrome and FireFox show the alert but with empty data, IE fails with access denied.
Darin Dimitrov
+1 Some browsers allow this *if* the page sending the request is hosted from the filesystem or perhaps localhost. Firefox and Chrome are more strict by default.
patrick dw
A: 

Are you opening the html file directly from a file (e.g. does the address bar say file://usr/path/to/the/file)?

We've found chrome won't let you 'ajax' in files from other domains when running under file://. However, in Safari it works fine.
Best solution for us is to use something like MAMP to run a local Apache server.

Ben Clayton
+1  A: 

Although i can't remember if i changed any IE option, the Darin Dimitrov seems explain my problem.

I found some tricks can be used (beyond the Dimitrov answer):

Zé Carlos