api

2016-06-08 44 views
11

Havayı ve haftanın birçok günü sıcaklığını görüntüleyen bir hava uygulama yapma çalışıyorum getirme ile XML getirme nasıl. Şu anda böyle bir görev için openweathermap API kullanıyorum, şu ki istediğim bilgiler (yani hava durumu) sadece xml formatında geliyor. ben de getirme api kullanmak isteyen akademik nedenlerle ES6 (ES2015) onu yeniden ediyorum ama getirme yöntemi ayrıştırır beri, sadece bir hata verir beri. böylece nasıl alabilirim veya daha iyi bir yol var mı? response => response.json() yanıtı geçerli bir JSON nesnesi (bu XML) olmadığından:api

let apis = { 
    currentWeather: { //get user selected recomendation weather 
     api:"http://api.openweathermap.org/data/2.5/forecast/daily?lat=", 
     parameters: "&mode=xml&units=metric&cnt=6&APPID=/*api key*/", 
     url: (lat, lon) => { 
      return apis.currentWeather.api + lat + "&lon=" + lon + 
        apis.currentWeather.parameters 
     } 
    } 
}; 
function getCurrentLoc() { 
    return new Promise((resolve, reject) => navigator.geolocation 
              .getCurrentPosition(resolve, reject)) 
} 
function getCurrentCity(location) { 
    const lat = location.coords.latitude; 
    const lon = location.coords.longitude; 
    return fetch(apis.currentWeather.url(lat, lon)) 
    .then(response => response.json()) 
    .then(data => console.log(data)) 
} 
getCurrentLoc() 
.then(coords => getCurrentCity(coords)) 

cevap

7

hata bu işlevinden geliyor sanırım.

Bildiğim kadarıyla, fetch için yerel XML ayrıştırıcısı yok, ancak yanıtı metin olarak kullanabilir ve gerçek ayrıştırma işlemini yapmak için üçüncü taraf bir araç kullanabilirsiniz; örneğin jQuery'de $.parseXML() işlevi vardır. yazılabilir

function getCurrentCity(location) { 
    const lat = location.coords.latitude; 
    const lon = location.coords.longitude; 
    return fetch(apis.currentWeather.url(lat, lon)) 
     .then(response => response.text()) 
     .then(xmlString => $.parseXML(xmlString)) 
     .then(data => console.log(data)) 
} 
+3

Ben hiçbir yerli XML ayrıştırıcı var olduğunu teyit edebilir getir. Https://developer.mozilla.org/en-US/docs/Web/API/Response#Methods sayfasına bakın. – Marco

13

yerli DOMParser getCurrentCity (konum) kullanarak::

Bu gibi bir şey olacaktır

function getCurrentCity(location) { 
 
    const lat = location.coords.latitude; 
 
    const lon = location.coords.longitude; 
 
    return fetch(apis.currentWeather.url(lat, lon)) 
 
     .then(response => response.text()) 
 
     .then(str => (new window.DOMParser()).parseFromString(str, "text/xml")) 
 
     .then(data => console.log(data)) 
 
}