How can I use $.ajax to retrieve normal JSON as JSONP?
Asked Answered
A

1

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){

    }
});
Ar answered 28/6, 2014 at 21:53 Comment(3)
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 !Bang
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.Sycophancy
@jcaron: That's exactly what JSONP is used for.Keelung
K
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){

    }
});
Keelung answered 28/6, 2014 at 22:10 Comment(4)
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?Ar
@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.Keelung
I see. Was your proxy difficult to set up? Would really like to know how it is done!Ar
@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.Keelung

© 2022 - 2024 — McMap. All rights reserved.