Zé Carlos
Zé Carlos

Reputation: 3807

jQuery: Can't run $.get (http get) on Chrome

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"></script> 
    <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

Upvotes: 2

Views: 865

Answers (3)

Z&#233; Carlos
Z&#233; Carlos

Reputation: 3807

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):

Upvotes: 1

Ben Clayton
Ben Clayton

Reputation: 82227

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.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039170

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.

Upvotes: 8

Related Questions