我正在寫一個小型的JavaScript程序,當用戶點擊地圖時,可以通過Web調用來提取天氣信息。這是我的代碼:XMLHttpRequest什麼都不返回?
//get the three letter airport code
var text = kmlEvent.featureData.name;
//service to get woeid
var woeid_url = 'http://where.yahooapis.com/geocode?name=';
xmlhttp = new XMLHttpRequest();
//has to be sync, since next request depends on it
xmlhttp.open('POST', woeid_url + text, false);
xmlhttp.send(null);
//now we get the relevent info from the XML
xmlDoc = xmlhttp.responseXML;
woeid_xml = xmlDoc.getElementsByTagName('woeid');
//parse the xml and get the woeid
woeid = woeid_xml[0].childNodes[0].nodeValue;
//with the woeid found, we can make the weather request
weatherhttp = new XMLHttpRequest();
var weather_url = 'http://weather.yahooapis.com/forecastrss?w=' + woeid + '&u=f';
//this is async
weatherhttp.open('POST', weather_url, true);
weatherhttp.onreadystatechange = function() {
if (weatherhttp.readyState == 4) {
alert(weatherhttp.status);
}
}
weatherhttp.send(null);
它打電話給雅虎得到用戶點擊位置的可怕。這工作,我得到的蠻幹很好。但是,當我將第二個呼叫作爲天氣服務時,它將返回任何內容並將0作爲狀態碼。
如果我改變第二部分是同步而不是異步,我仍然得到相同的錯誤。有沒有人看到我在做什麼錯了?如果我將weather_url複製到瀏覽器中,則加載它就好了。我不明白爲什麼第一部分可行,但不是第二部分。我對JavaScript和AJAX很陌生,所以我真的不知道我在做什麼。
我使用的瀏覽器是FireFox,如果有幫助的話。
我第一次打電話給'where.yahooapis.com'是在不同的域,雖然,那是有效的。但後來'weather.yahooapis.com'沒有。同源策略會導致這種行爲嗎? – TheEnigmaMachine 2012-03-27 16:24:03
您可以通過構建代理完全繞過同源策略,即創建處理請求並將其轉發給雅虎的頁面。比如'myserver.com/where.php?name=blah'就會向'http://where.yahooapis.com/geocode?name=blah'發出一個服務器端請求,並將結果返回給調用者。 – mellamokb 2012-03-27 16:33:17
我剛剛在jsfiddle中嘗試了你的代碼,並得到這個錯誤:'XMLHttpRequest無法加載http://weather.yahooapis.com/forecastrss?w=12519826&u=f。 Access-Control-Allow-Origin不允許Origin http://fiddle.jshell.net。這似乎是一個SOP問題。你能看到在螢火蟲中引發任何錯誤嗎? – dontGoPlastic 2012-03-27 18:29:27