How can I use $.ajax to retrieve normal JSON as JS

2019-09-03 20:02发布

问题:

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

    }
});

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

    }
});