0

I have a normal JSON feed that I am polling at a url (normalJSONfeed). I am getting the cross origin policy error each time. How can I alter the $.ajax function to get around this limitation when I do not have any way of changing the JSON feed (in other words I can not wrap the JSON feed in a function call).

$.ajax({
    type : "GET",
    dataType : "jsonp",
    url : '/normalJSONfeed',
    data : {}
    success: function(obj){

    }
});
mc110
  • 2,825
  • 5
  • 20
  • 21
Startec
  • 12,496
  • 23
  • 93
  • 160
  • 2
    You can't, the server has to actually send JSONP, there's nothing you can do to change the data on the clientside. You could use your own server as a proxy though ! – adeneo Jun 28 '14 at 21:58
  • AFAIK, `cross origin` has no relationship whatsoever with JSON vs VSONP. It just means that you are trying to query an URL that is not on the same server (protocol+domain+port) as the page it is called from. – jcaron Jun 28 '14 at 22:02
  • @jcaron: That's exactly what JSONP is used for. – Guffa Jun 28 '14 at 22:03

1 Answers1

1

There is nothing that you can change in the code only that lets you request JSON as JSONP. As the JSONP requests uses a script tag to request the data, there is no point between the data being loaded and being handled where you can affect it.

If you can't change what the server sends, you need a server in between that can change the response before it arrives. I have set up a proxy server that does change a JSON response to a JSONP response. Request the proxy page and send along the URL of the resource that returns JSON as a parameter.

Example:

$.ajax({
    dataType : "jsonp",
    url : 'http://jsonp.guffa.com/Proxy.ashx?url=' + encodeURIComponent('www.someserver.com/normalJSONfeed'),
    success: function(obj){

    }
});
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • Brilliant. And I assume I can rely on your proxy server in perpetuity ;)? No seriously, can I? Also, is there any other hack or technique to use **on the browser side** , to sidestep this policy? – Startec Jun 28 '14 at 22:13
  • @Startec: I set up the server mostly for testing purposes, but I have no plans to take it down. There is nothing that you can do in the browser to get around the same origin policy. To get around it you need to at least be able to add files to the server. – Guffa Jun 28 '14 at 22:17
  • I see. Was your proxy difficult to set up? Would really like to know how it is done! – Startec Jun 28 '14 at 22:22
  • @Startec: The principe is simple, it's just a page that does a request and returns the response after wrapping it in code for a function call, but getting headers and everything right was a bit tricky. – Guffa Jun 28 '14 at 22:33