3

I am very new to jQuery and AJAX,I am trying following code,just simple http get request.

<html>
<head>
</head>
<body>
    <script src = "jquery-2.1.4.js"></script>
    <script src = "app.js"></script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                $.get("http://google.com", function(data, status){
                    alert("Data: " + data + "\nStatus: " + status);
                });
            });
        });
    </script>
    <button>Send an HTTP GET request to a page and get the result back</button>
</body>
</html>

and I am getting following error

XMLHttpRequest cannot load http://google.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'file://' is therefore not allowed access.

Please help me what am I missing.

dingo_d
  • 11,160
  • 11
  • 73
  • 132
newhorizens
  • 107
  • 1
  • 9

3 Answers3

2

Same origin policy will not let you access resources hosted on a different server. In your case, if the target system is not under your control, you can look at utilities like jsonp which can help you fire cross domain requests.

Pavan Andhukuri
  • 1,547
  • 3
  • 23
  • 49
0

So according to SOP which is same origin policy Under this policy, a web browser permits scripts contained in a first web page to access data in a second web page, but only if both web pages have the same origin same origin means same URL Scheme , Host name and Port number. to get over this you can use like

$.ajax({
    url: "http://google.com",
    dataType: "jsonp"},
    success: function( response ) {
        console.log( response ); // server response
    }
})

Read more on JSONP.

Roli Agrawal
  • 2,356
  • 3
  • 23
  • 28
-1

It is simply cross domain request which you are making from your application, things you have to make sure to avoid this error,

1) Enable cors in your application to make a cross domain application.
2) You can use JSONP while making your request to cross domain instead of GET.

Please go through this link you will get more detail about the "CORS" https://developers.google.com/api-client-library/javascript/features/cors

nitin
  • 156
  • 2
  • 13