jQuery “getJSON” from an external domain that doesn't support JSON-P output

ぐ巨炮叔叔 提交于 2019-12-08 13:23:36

问题


I'm trying to grab data from a JSON on an external site but the site doesn't support JSON-P output. This is an example of non-working code, but gives a good idea of what I'm trying to achieve:

$.getJSON("http://www.bom.gov.au/fwo/IDV60901/IDV60901.94868.json", function(data){
    //Process data here
});

Are there ways around this other than locally hosting the data or downloading and processing it with an AJAX/PHP call? I would rather not have the server serve or download the data and rather have the user's browser grab it directly.

Thanks in advance!


回答1:


The Same Origin Policy of most browsers would not let you do this without a willing external server or a server-side proxy. There are a few hacks you could try out with flash:

http://flxhr.flensed.com/

This assumes your user has flash installed, but generally, if they have javascript installed, they also have flash...

OR

If the data you are looking for came as a feed somewhere, you could pass it through Yahoo Pipes and they will return jsonp for you.

Best of luck!




回答2:


Easiest option would be to run the json call through a PHP proxy script, like this one:

<?php
// PHP Proxy
// Loads a file from any location.
// Author:Paulo Fierro
// January 29, 2006
// usage: proxy.php?url=http://mysite.com/myxml.xml

$session = curl_init($_GET['url']);                    
curl_setopt($session, CURLOPT_HEADER, false);          
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);   
$xml = curl_exec($session);                            
echo $xml;        
curl_close($session); 

?>

and use that as the source of you ajaxCall

$.getJSON("proxy.php?url=http%3A%2F%2Fwww.bom.gov.au%2Ffwo%2FIDV60901%2FIDV60901.94868.json", function(data){


来源:https://stackoverflow.com/questions/1845715/jquery-getjson-from-an-external-domain-that-doesnt-support-json-p-output

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