2013-09-20 5 views
4

Я пишу немного JavaScript, чтобы извлекать информацию из JSON, которая содержит вызов имени, долготы, широты и openweather API. Мне нужно, чтобы получить информацию API из вызова API в HTML-страницу, чтобы вы могли получать прогноз погоды для каждой информации. У меня есть два элемента, работающих отдельно, но не могу понять, как заставить их работать вместе.API OpenWeather - вытаскивание данных JSON

Помогите, пожалуйста? :-)

Sample API погоды от d.weather

api.openweathermap.org/data/2.5/forecase?lat=50.8609&lon=-0.08014&&units=metric 

HTML страницы для вытягивать openweather данных JSON

<html> 
<head> 
<title>Weather</title> 
    <meta charset="utf-8"> 

    <script src="http://code.jquery.com/jquery-1.7.min.js" ></script> 
    <script src="http://code.jquery.com/ui/1.7.0/jquery-ui.js" ></script> 

<script> 
function getWeather(callback) { 
    var weather = 'http://api.openweathermap.org/data/2.5/forecast?lat=51.5072&lon=0.1275&units=metric'; 
    $.ajax({ 
     dataType: "jsonp", 
     url: weather, 
     success: callback 
    }); 
} 

// get data: 
getWeather(function (data) { 
    console.log('weather data received'); 
    console.log(data.list[0].weather[0].description); 
    console.log(data.list[0].weather[0].main); 
}); 

getWeather(function (data) { 
    document.write('weather data received'); 
    document.write('<br>'); 
    document.write(data.list[0].weather[0].description); 
    document.write('<br>'); 
    document.write(data.list[0].weather[0].main); 
    document.write('<br>'); 
    document.write(data.list[0].main.temp); 
    document.write('<br>'); 
    document.write(data.list[0].main[0].dt_txt); 
    document.write('<br>'); 
}); 
</script> 
</body> 
</html> 

Html страниц для вытягивать данные JSON

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script> 
<!-- Javascript --> 

<script type="text/javascript"> 
function loadUrl(newLocation){ 
    window.location = newLocation; 
    return false; 
} 
</script> 

<script type="text/javascript"> 
$(document).ready(function(){ 
    $("#btn382").click(function(){  
     /* set no cache */ 
     $.ajaxSetup({ cache: false }); 

     $.getJSON("weather.json", function(data){ 
      var html = []; 

      /* loop through array */ 
      $.each(data, function(index, d){   
       html.push("Team : ", d.Teams, ", ", 
          "Long : ", d.Long, ", ", 
          "Lat : ", d.Lat, ", ", 
       "Weather : ", d.Weather, "<br>");   
      }); 


      $("#div381").html(html.join('')).css("background-color", "orange"); 
     }).error(function(jqXHR, textStatus, errorThrown){ /* assign handler */ 
      /* alert(jqXHR.responseText) */ 
      alert("error occurred!"); 
     }); 
    }); 
}); 
</script> 

<!-- HTML --> 
<a name="#ajax-getjson-example"></a> 
<div id="example-section38"> 
    <div>Football weather</div> 
    <div id="div381"></div> 
    <button id="btn382" type="button">Team location</button> 
</div> 

weather.json

{ 
    "Teams":"Wycombe Wanderers", 
    "Long":-0.800299, 
    "Lat":51.6306, 
    "Weather":" api.openweathermap.org/data/2.5/weather?lat=51.6306&lon=-0.800299&mode=html" 
    }, 
    { 
    "Teams":"Livingston", 
    "Long":-3.52207, 
    "Lat":55.8864, 
    "Weather":" api.openweathermap.org/data/2.5/weather?lat=55.8864&lon=-3.52207&mode=html" 
    }, 
    { 
    "Teams":"Brighton and Hove Albion", 
    "Long":-0.08014, 
    "Lat":50.8609, 
    "Weather":" api.openweathermap.org/data/2.5/weather?lat=50.8609&lon=-0.08014&mode=html" 
    }, 
+0

Вы можете добавить их в jsfiddle? – Andy

+0

Подождите, откуда вы получаете «команды»? Это не будет в данных о погоде. Вы имеете в виду «город»? – Andy

+0

Привет, Энди, команды приходят из json-файла, который я вручную ввел в это поле. – Grimlockz

ответ

5

У меня есть основы, которые должны помочь вам на вашем пути. Это mashup из ваших двух страниц.

Сначала я поменял вашу функцию getWeather, чтобы получить прогноз погоды, а не прогноз. Он принимает параметр city и добавляет этот параметр к данным перед вызовом обратного вызова.

function getWeather(city, callback) { 
    var url = 'http://api.openweathermap.org/data/2.5/weather'; 
    $.ajax({ 
    dataType: "jsonp", 
    url: url, 
    jsonCallback: 'jsonp', 
    data: { q: city }, 
    cache: false, 
    success: function (data) { 
     data.city = city; 
     callback(data); 
    } 
    }); 
} 

Здесь вместо ваших команд JSON я сделал один в виде объекта JS, с Арсеналом и Ливерпулем и их соответствующими городами, как данные. Функция перемещается по объекту, извлекает название города и передает его на номер getWeather. Данные возвращаются и добавляются в div.

$(document).ready(function() { 

    $("#btn382").click(function() { 

    var teams = { 
     arsenal: { city: 'london' }, 
     liverpool: { city: 'liverpool' } 
    }; 

    for (var team in teams) { 
     var city = teams[team].city; 
     getWeather(city, function(data) { 
     var html = []; 
     html.push('<div>') 
     html.push('City: ', data.city, ', '); 
     html.push('Lat: ', data.coord.lat, ', '); 
     html.push('Lon: ', data.coord.lon, ', '); 
     html.push('Weather: ', data.weather[0].description); 
     html.push('</div>') 
     $("#div381").append(html.join('')).css("background-color", "orange"); 
     }); 
    } 

    }); 
}); 

Надеюсь, это даст вам несколько идей о том, как решить этот проект.

See it working here.

+0

Andy благодарит за вашу помощь. Я могу видеть, что у вас есть, и его отличная помощь. Я добавил weather.json, чтобы вы могли видеть, что я пытался сделать. – Grimlockz

+0

Если это лучший ответ, можете нажать на галочку ? – Andy

+0

Извините, конечно, – Grimlockz

-1

почему бы вам не использовать XML вместо JSON легко разобрать, я использую его в моем веб-сайте weathercase, попробуйте API провайдера yr.no

+0

Потому что JSON намного быстрее разбирается. Практически в 10 раз эффективнее. –

+0

Любые доказательства, что JSON быстрее – sakher

+0

Вот эксперимент на Python, который иллюстрирует мое утверждение: https://github.com/concolato/data_processing/tree/master/imageXMLtoCVSTestPY, и поскольку Python - это язык на основе C, я бы ожидал, что аналогичный приводит к C/C++, Java и PHP. Но вы можете попробовать это на другом языке, чтобы подтвердить, хотите ли вы. –

0

Я сделал полный пример. Для меня это сработало:

HTML файл:

<!DOCTYPE html> 
    <html> 
    <head> 
     <script src="http://code.jquery.com/jquery-2.1.0.min.js"></script> 
     <meta charset="utf-8"> 
     <title>jQuery Ajax</title> 
     <link rel="stylesheet" href="css/ajx-json-styles.css"> 

     <script> 
     function displayParsedData(data){ 
      /* Working with the 'data' object (not string) here, now we can access the different properties available.*/ 
      text = '<b>Name: </b>' + data.list[0].name + '<br/>'; 
      text += '<b>message: </b>' + data.message + '<br/>'; 
      text += '<b>Current Temperature: </b>' + data.list[0].main.temp + ' F<br/>'; 
      text += '<b>Weather Conditions: </b>' + data.list[0].weather[0].description + '<br/>'; 
      $('#parsed_json').append(text); 
     } 
     </script> 

     <script> 
     function test1() { 
      getWeather(function (data) { 
       $("#raw_json").html('<h2>callback</h2><pre>' + JSON.stringify(data, null, 2) + '</pre>'); 
       displayParsedData(data);   
      }); 
     } 

     function getWeather(callback) { 
      var weather = 'http://openweathermap.org/data/2.1/find/city?lat=8.2924495&lon=-62.7373258'; 
      $.ajax({ 
      dataType: "jsonp", 
      url: weather, 
      success: callback 
      }); 
     } 
     </script> 

     <script> 
     function test2() { 
      $.ajax({ 
      url: 'http://openweathermap.org/data/2.1/find/city?lat=8.2924495&lon=-62.7373258', 
      type: 'GET', 
      dataType:"jsonp", 
      success: function(data) { 
       $("#raw_json").html('<h2>$.ajax</h2><pre>' + JSON.stringify(data, null, 2) + '</pre>'); 
       displayParsedData(data); 
      }, 
      error: function(jqXHR, textStatus, error) { 
       alert("error: " + jqXHR.responseText); 
      } 
      }); 
     } 
     </script>  

     <script> 
     function test3() { 
      $.getJSON('http://openweathermap.org/data/2.1/find/city?lat=8.2924495&lon=-62.7373258&callback=?', function(data) { 
       $("#raw_json").html('<h2>getJSON</h2><pre>' + JSON.stringify(data, null, 2) + '</pre>'); 
       displayParsedData(data); 
      }) 
      .done(function() { 
      alert("second success"); 
      }) 
      .fail(function() { 
      alert("error"); 
      }); 
     } 
     /*$.getJSON('http://openweathermap.org/data/2.1/find/city?lat=13.3428&lon=-6.2661&cnt=10&callback=?', function(data) { console.log(data); });*/ 
     </script> 

     <script> 
     $(document).ready(function(){ 
      $("#btn382").click(function(){  
       /* set no cache */ 
       $.ajaxSetup({ cache: false }); 

       $.getJSON("weather.json", function(data){ 
        for (var team in data) { 
        var html = []; 
        html = '<div class="item"><b>Team: </b>' + data[team].Teams + '<br/>'; 
        html += '<b>Lat: </b>' +data[team].Lat + '<br/>'; 
        html += '<b>Lon: </b>' + data[team].Lon + '<br/>'; 
        html += '<b>Weather: </b>' + data[team].Weather + '<br/></div>'; 
        $("#div381").append(html); 
        } 
       }) 
       .error(function(jqXHR, textStatus, errorThrown){ /* assign handler */ 
        /* alert(jqXHR.responseText) */ 
        alert("error occurred!"); 
       }); 
      }); 
     }); 
     </script> 

    </head> 
    <body> 
     <div id="example-section38"> 
     <div>Otra fuente</div> 
     <div id="div381"></div> 
     <button id="btn382" type="button">Team location</button> 
     </div> 

     <div id="raw_json"></div> 
     <div id="parsed_json"></div> 

     <button onclick="test1();">callback</button> 
     <button onclick="test2();">$.ajax</button> 
     <button onclick="test3();">getJSON</button> 
    </body> 
    </html> 

weather.json

[ 
    { 
     "Teams":"Wycombe Wanderers", 
     "Lon":-0.800299, 
     "Lat":51.6306, 
     "Weather":" api.openweathermap.org/data/2.5/weather?lat=51.6306&lon=-0.800299&mode=html" 
    }, 
    { 
     "Teams":"Livingston", 
     "Lon":-3.52207, 
     "Lat":55.8864, 
     "Weather":" api.openweathermap.org/data/2.5/weather?lat=55.8864&lon=-3.52207&mode=html" 
    }, 
    { 
     "Teams":"Brighton and Hove Albion", 
     "Lon":-0.08014, 
     "Lat":50.8609, 
     "Weather":" api.openweathermap.org/data/2.5/weather?lat=50.8609&lon=-0.08014&mode=html" 
    } 
] 

AJX-JSON-styles.css

#raw_json { 
    border:1px solid #333; 
    background-color:#ccc; 
    padding: 2em; 
    word-wrap: break-word; 
    margin-bottom: 2em; 
    width: 40%; 
    float: left; 
} 
#parsed_json { 
    padding:2em; 
    border: 1px solid blue; 
    width: 40%; 
    float: right; 
} 
h2 { 
    margin:0; 
    padding:0; 
} 
.item{ 
    padding-bottom: 0.25em; 
    padding-top: 0.25em; 
    background-color: #E9BB18; 
    border: 1px solid white; 
} 

Смежные вопросы