代码(对不起,如果它太多):
var button=document.getElementById('submit');
var zipcode;
var lat;
var lng;
var weather;
var iconId;
var temp;
/*takes what the user enters*/
button.addEventListener('click',getValue);
function getValue(event){
event.preventDefault();
zipcode=document.getElementById('zipcode').value;
getCity();
}
//API request to Google Geocode
function getCity(){
var req=new XMLHttpRequest;
req.onreadystatechange=function(){
if(this.readyState==4&&this.status==200){
var myData=JSON.parse(this.responseText);
var myCity=myData.results[0].address_components[1].short_name;
lat=myData.results[0].geometry.location.lat;
lng=myData.results[0].geometry.location.lng;
document.getElementById('lat').innerHTML=lat;
document.getElementById('lng').innerHTML=lng;
document.getElementById('city').innerHTML=myCity;
}//if function end
}//onreadystate function end
req.open('GET','https://maps.googleapis.com/maps/api/geocode/json?address='+zipcode, true);
req.send();
getWeather();
}
//API request Dark Sky Weather
function getWeather(){
var request=XMLHttpRequest;
request.onreadystatechange=function(){
if(this.readyState==4&&this.status==200){
var myWeather=JSON.parse(this.responseText);
weather=myWeather.currently.summary;
document.getElementById('weather').innerHTML=weather;
console.log(myWeather);
}//if ends
}//onready end
request.open('GET','https://api.darksky.net/forecast/6231bad7d2bf09aa53301a4227b7c1af/'+lat+','+lng, true);
request.send();
}
<form>
<input type=text placeholder='zipcode' id='zipcode'></input>
<input type='submit' id='submit'></input>
</form>
<ol>
<li>City Name: <span id='city'></span></li>
<li>Latitude: <span id='lat'></span></li>
<li>Longitude: <span id='lng'></span></li><br>
<li>Temperature(F): <span id='temp'></span></li>
<li>Icon: <span id='icon'></span></li>
<li>Weather: <span id='weather'></span></li><br>
<li>Wind(mph): <span id='wind'></span></li>
<li>Sunrise: <span id='sunrise'></span></li>
<li>Sunset: <span id='sunset'></span></li>
</ol>
好的,这是我的代码的逻辑 . 您输入zipcode并按'submit',并触发具有回调函数'getValue'的Event Listener,它将zipcode存储在变量中并执行getCity()函数,该函数将zipcode转换为City Name和Lat和Lng .
我不知道在哪里执行使用Lat和Lng获取天气条件的getWeather()函数 . 我最初把它放在getCalue()函数定义中的getCity()之后,但 I thought that would leaves no time for the Lat and Lng value to be obtained from the first API. 所以我放入了getCity()函数定义 .
getCity()函数运行良好,将zipcode转换为City Name和Lat Lng . 但问题是getWeather()函数应返回类似'Rainy'的描述 .
Chrome控制台中出错:
EDIT :我添加'new'关键字 . var request = new XMLHttpRequest;这是一个愚蠢的错字 . 这是新错误:
!!EDIT 2: HUGE DISCOVERY: 我想我知道为什么 . 但我不知道如何解决它 . 这是SCOPE!我在getWeather()函数的定义中尝试 console.log(lat+' and '+lng); ,控制台说'undefinedandundefined' . 我可以获得经度和纬度的唯一地方是如果我将console.log放在getCity()函数的定义中,其中第一个API将输入的zipcode转换为lat和lng .
1 回答
需要实例化请求对象 . 试着这样做:
var request = new XMLHttpRequest();
.编辑:您需要明确标记请求标头 .
request.setRequestHeader('Access-Control-Allow-Origin', '*');