index.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. var selects = document.querySelector('.selects');
  2. var weatherDiv = document.querySelector('.weather');
  3. function get(url){
  4. return new Promise(function(resolve,reject){
  5. var xhr = new XMLHttpRequest();
  6. xhr.open('GET',url,true);
  7. xhr.onload = function(){
  8. if(xhr.status == 200){
  9. resolve(JSON.parse(xhr.responseText));
  10. }
  11. else{
  12. reject(xhr.statusText);
  13. }
  14. }
  15. xhr.onerror = function(){
  16. reject('not found');
  17. }
  18. xhr.send();
  19. });
  20. }
  21. function show(obj){
  22. var weather = obj.query.results.channel.item.description;
  23. var resWeather = weather.replace(/href|CDATA|[\!]|[\[]|[\]]/g,"");
  24. var resWeather2 = resWeather.slice(1,resWeather.length - 1);
  25. var resWeather3 = resWeather2.replace(/Full Forecast at Yahoo Weather/g,"");
  26. var resWeather4 = resWeather3.slice(0,resWeather3.length - 28);
  27. weatherDiv.innerHTML = resWeather4;
  28. }
  29. get('https://raw.githubusercontent.com/David-Haim/CountriesToCitiesJSON/master/countriesToCities.json').then(function(object){
  30. var keys = Object.keys(object);
  31. var select = document.createElement("select");
  32. for (var i = 0; i < keys.length; i++) {
  33. var option = document.createElement("option");
  34. option.innerHTML = keys[i];
  35. option.value = keys[i];
  36. select.appendChild(option);
  37. }
  38. select.onchange = function(e){
  39. console.log(this.value)
  40. console.log(document.getElementById("main").value)
  41. var select = document.createElement("select");
  42. for (var i = 0; i < object[this.value].length; i++) {
  43. var option = document.createElement("option")
  44. option.innerHTML = object[this.value][i];
  45. select.appendChild(option);
  46. }
  47. if(selects.children.length > 1){
  48. selects.replaceChild(select, document.getElementById("main").nextElementSibling);
  49. }
  50. else
  51. selects.appendChild(select);
  52. get("https://query.yahooapis.com/v1/public/yql?" + 'q=' + encodeURIComponent("select * from weather.forecast where woeid in (select woeid from geo.places(1) where text=\'" + select.value + "\') and u='c'") + '&format=json').then(function(obj){
  53. show(obj);
  54. }).catch(function(){
  55. weatherDiv.setAttribute("heigt", "400px")
  56. weatherDiv.innerHTML = "loading...";
  57. });
  58. select.onchange = function(){
  59. get("https://query.yahooapis.com/v1/public/yql?" + 'q=' + encodeURIComponent("select * from weather.forecast where woeid in (select woeid from geo.places(1) where text=\'" + this.value + "\') and u='c'") + '&format=json').then(function(obj){
  60. show(obj);
  61. })
  62. }
  63. }
  64. selects.appendChild(select);
  65. select.id = "main"
  66. }).catch(function(error){
  67. console.log(error);
  68. })