Jquery $ .getJSON不能运行Chrome和Firefox,但它可以在IE中运行

时间:2012-03-07 09:55:01

标签: jquery json getjson

我试图在我的网站上使用yahoo wheather api,因此我写了一个简单的脚本如下:

<button>show</button><br />

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var url='http://weather.yahooapis.com/forecastjson?w=2344116&u=c';
var query;
    $('button').click(function(){
        $.getJSON(url, function(json) {
        alert(json.units.temperature);
        });
    });
});
</script>

它适用于IE(我正在获取警报弹出窗口),但它在chrome和firefox中不起作用。另外,我验证了JSON输出;

{
    "units": {
        "temperature": "C",
        "speed": "km/h",
        "distance": "km",
        "pressure": "mb"
    },
    "location": {
        "location_id": "TUXX0014",
        "city": "Istanbul",
        "state_abbreviation": "*",
        "country_abbreviation": "TU",
        "elevation": 92,
        "latitude": 41.01,
        "longitude": 28.95
    },
    "wind": {
        "speed": 10,
        "direction": "NE"
    },
    "atmosphere": {
        "humidity": "34",
        "visibility": 9.99,
        "pressure": 1016,
        "rising": "steady"
    },
    "url": "http://weather.yahoo.com/forecast/TUXX0014.html",
    "logo": "http://l.yimg.com/a/i/us/nt/ma/ma_nws-we_1.gif",
    "astronomy": {
        "sunrise": "06:29",
        "sunset": "18:03"
    },
    "condition": {
        "text": "Fair",
        "code": "34",
        "image": "http://l.yimg.com/a/i/us/we/52/34.gif",
        "temperature": 9
    },
    "forecast": [
        {
            "day": "Today",
            "condition": "Mostly Sunny",
            "high_temperature": 8,
            "low_temperature": 2
        },
        {
            "day": "Tomorrow",
            "condition": "Mostly Cloudy",
            "high_temperature": 8,
            "low_temperature": 3
        }
    ]
}

任何帮助将不胜感激。

最诚挚的问候。

奥斯曼。

2 个答案:

答案 0 :(得分:0)

我试过了:http://jsfiddle.net/arXt2/我的错误日志说:

XMLHttpRequest cannot load http://weather.yahooapis.com/forecastjson?w=2344116&u=c. 
Origin http://fiddle.jshell.net is not allowed by Access-Control-Allow-Origin.

你想要的是cross side scripting。见How to make an ajax with JQuery with cross site scripting?

答案 1 :(得分:0)

跨源浏览器问题。

了解更多信息:http://enable-cors.org/

Using the Yahoo Weather API with JSON and the script tag