jQuery的$ .getJSON不工作Chrome和Firefox,但它在IE

问题描述:

工作

我试图使用雅虎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 
     } 
    ] 
} 

任何帮助将不胜感激。

最好的问候。

奥斯曼。

+0

中的jsfiddle尝试这一点,让我在Chrome和Firefox的一个'接入控制允许Origin'失败。 – steveoh 2012-03-07 10:02:42

我试过了: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?

+0

似乎我需要使服务器端脚本来启用代理服务器。 我正在处理sharepoint environment.I在page_load函数中添加了以下代码,但没有发生任何事情。我仍然有问题:( Response.AppendHeader(“访问控制允许来源”,“*”); – 2012-03-14 14:41:44

跨源浏览器问题。

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

尝试 Using the Yahoo Weather API with JSON and the script tag

+0

卢卡感谢您的快速回复 我尝试了使用雅虎天气API与JSON和脚本标签,但问题仍然存在 奇怪的事情我可以从类似的脚本解析数据从twitter或flickr – 2012-03-07 10:22:53

+0

似乎我需要使服务器端脚本来启用代理 我正在处理sharepoint environment.I添加了以下代码在page_load函数中,但没有发生任何事情。我仍然有问题:( Response.AppendHeader(“Access-Control-Allow-Origin”,“*”); – 2012-03-14 14:45:26