Search code examples
jqueryajaxgetjson

Jquery.getJSON is not able to handle cross browser between domain though it should be


I am trying to create a jquery widget which loads some data from the server and put it in a container in clients browser. So the issue of cross browser call in different domain needs to be taken care of. To do so I used $.getJSON. The following shows my javascript code:

(function() {

// Localize jQuery variable
var jQuery;

/** ****** Load jQuery if not present ******** */
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.4.2') {
    var script_tag = document.createElement('script');
    script_tag.setAttribute("type", "text/javascript");
    script_tag
            .setAttribute("src",
                    "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js");
    if (script_tag.readyState) {
        script_tag.onreadystatechange = function() { // For old versions
                                                        // of IE
            if (this.readyState == 'complete'
                    || this.readyState == 'loaded') {
                scriptLoadHandler();
            }
        };
    } else { // Other browsers
        script_tag.onload = scriptLoadHandler;
    }
    // Try to find the head, otherwise default to the documentElement
    (document.getElementsByTagName("head")[0] || document.documentElement)
            .appendChild(script_tag);
} else {
    // The jQuery version on the window is the one we want to use
    jQuery = window.jQuery;
    main();
}

/** ****** Called once jQuery has loaded ***** */
function scriptLoadHandler() {
    // Restore $ and window.jQuery to their previous values and store the
    // new jQuery in our local jQuery variable
    jQuery = window.jQuery.noConflict(true);
    // Call our main function
    main();
}

/** ****** Our main function ******* */
function main() {
    jQuery(document)
            .ready(
                    function($) {
                        getTodaysAd();
                        function getTodaysAd() {
                            var url = "http://localhost:8080/TJ/ads/adsLoader";
                            $
                                    .getJSON(
                                            url,
                                            function(data) {
                                                console.log(data);
                                                $("#todaysAd")
                                                        .append(
                                                                "<a id=\"adsDestination\"><img id=\"adsImg\"></a></img>");
                                                $("#adsImg").attr({
                                                    "href" : data[0].href,
                                                    "src" : data[0].imgurl
                                                });
                                                $("#adsDestination").attr({
                                                    "href" : data[0].href
                                                });
                                            });
                        }

                    });
    }

  })(function() {
  }); // We call our anonymous function immediately

and in order to run it user just need to add the following to the page:

<script src="http://localhost:8080/TJ/js/embed.js" type="text/javascript"></script>
<div id="todaysAd" class="panel-heading"></div>

However still I get the following error:

XMLHttpRequest cannot load http://localhost:8080/TJ/ads/adsLoader. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3003' is therefore not allowed access.

But as I searched $.getJSON should be able to handle this issue. Can anyone help?

******************UPDATE***************************

When I do the same thing but in the same domain everything works fine


Solution

  • While $.getJSON will in fact work cross-domain, you have to make sure that the domain you're fetching from is properly set up to allow the request.

    As the error states, this can be accomplished by putting an Access-Control-Allow-Origin header on the domain you're trying to fetch from.

    For more information about adding this header, take a look at this answer: How does Access-Control-Allow-Origin header work?