Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cross domain jquery get

Tags:

I saw some examples of cross domain with ajax but it doesn't work.

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    </head>
    <body>
        <script type="text/javascript" >
            $(document).ready(function () {
                var url = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=AssasNet&include_rts=1";

                $.get(url, function (data) {
                    console.log(data)
                    alert(data);
                });
            });
        </script>
    </body>
</html>

I try on chrome and the following error is given:

XMLHttpRequest cannot load http://api.twitter.com/1/statuses/user_timeline.json?screen_name=AssasNet&include_rts=1. Origin null is not allowed by Access-Control-Allow-Origin. 
like image 979
Ajouve Avatar asked Mar 12 '13 18:03

Ajouve


People also ask

What is cross domain AJAX request?

CORS is a mechanism that defines a procedure in which the browser and the web server interact to determine whether to allow a web page to access a resource from different origin. Figure 2. Cross domain ajax request. When you do a cross-origin request, the browser sends Origin header with the current domain value.

Can you do cross domain Ajax if so how?

Browser does not allow cross domain AJAX requests due to security issues. Cross-domain requests are allowed only if the server specifies same origin security policy. To enable CORS, You need to specify below HTTP headers in the server. Access-Control-Allow-Origin – Name of the domain allowed for cross domain requests.


1 Answers

You can't use $.get because that does an ajax call, which will be cross-origin and thus blocked by the Same Origin Policy, and the Twitter API you're trying to access doesn't support Cross-Origin Resource Sharing (or if it does, it doesn't allow either origin null or http://jsbin.com, which is the one I tried).

The API does support JSONP (which is not a true ajax call), though, so just changing the $.get to an $.ajax specifying JSONP works:

$.ajax({
  url: url,
  dataType: "jsonp",
  success: function (data) {
    console.log(data)
    alert(data);
  }
});

Live Example | Source

like image 87
T.J. Crowder Avatar answered Sep 22 '22 23:09

T.J. Crowder