Search code examples
javascriptjqueryajaxjsonsame-origin-policy

JQuery - Cross Domain Ajax call for JSON file without JSONP


I am trying to access a URL from a different domain, lets say www.url-one.com, that only serves up a JSON file and cannot serve up a JSONP file. This does not work for me using JQuery's ajax() function.

Here is what my code looks like:

    $.ajax({
        url : 'http://url-two.com'+sample,
        async : false,
        dataType : 'jsonp',
        crossDomain: true,
        success : function(data) {
            // Some Other Code
        }
     }

What can I do to work around the same origin policy without relying on JSONP? Thanks in advance - I am having major problems with the proxy thing but I heard that it's possible.


Solution

  • There are quite a few ways to do this, below i will mention 3 i have used myself in the past.

    The most common is to use Cross-Origin Resource Sharing (CORS).

    Basically the server which hosts the json file (lets call it server1), will need to set the Access-Control-Allow-Origin header correctly to allow the other server (lets call it server2) to access it.

    If you don't wish to or can't use CORS you can do one of the 2 following:

    1: use a re-write rule on server2 to redirect traffic for a certain path from server2 to server1.

    2: use a serverside proxy on server2 to fetch the json file.

    Setting either of these things up is completely dependent on your server setup, and i can't help you with that bit.