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

别说谁变了你拦得住时间么 提交于 2020-01-17 02:41:50

问题


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

    }
});


来源:https://stackoverflow.com/questions/24471288/how-can-i-use-ajax-to-retrieve-normal-json-as-jsonp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!