开发者

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


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.


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

  • use a PHP script:
    http://jquery-howto.blogspot.com/2009/04/cross-domain-ajax-querying-with-jquery.html

  • configure IE by editing regedit (not recomended):
    http://msdn.microsoft.com/en-us/library/dd565656(VS.85).aspx
    (I belive there's some other way to disable cross domain protection without editing regedit. But i couldn't find it)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜