javascript - 如何根据输入值呈现 JSON 数据

标签 javascript json

背景:

我正在开发一个小型项目,学习如何通过带有 JSON 文件的普通 JavaScript 使用 AJAX。我知道我可以使用 Jquery,但我正在学习很长的路,Jquery 将是下一个。

目标:

我的目标是能够输入一个城市,一旦我点击按钮,它就会呈现我输入的城市的当前天气。

问题:

我无法弄清楚并正在寻找有关如何从本质上获取值并将其附加到键并呈现我正在寻找的所有数据的指导。我的思考过程是引入输入值并将其与名称键进行比较,如果它们匹配则呈现结果。我只是想不通它在代码中的样子,因此非常感谢任何指导。

我有什么:

到目前为止,我能够通过使用以下文件进行硬编码来呈现我想要的内容:

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <title>Ajax3 - JSON(external api practice) File</title>
</head>
<body>
   <input id="city">
   <button id="button">Get Weather</button>
   <br><br>
   <h1>Weather</h1>
   <div id='weather'></div>
   <script>
           // Create an event listener
           document.getElementById('button').addEventListener('click', loadWeather);
           function loadWeather(){
               // console.log(city);
               let xhr = new XMLHttpRequest();
               xhr.open('GET', 'weather.json', true);
               xhr.onload = function(){
                   let city = document.getElementById('city').value;
                   // let keys = Object.keys(weather);
                   if(this.status == 200){
                       let weatherTest = JSON.parse(this.responseText);
                       let result = '';
                   //   weather.forEach((item, index) =>{
                       result += '<ul>'+
                           '<li>City: '+JSON.stringify(weatherTest[1].name )+ '</li>' +
                           '<li>Weather: '+JSON.stringify(weatherTest[1].weather[0].description )+ '</li>' +
                           '<li>Latitude: '+JSON.stringify(weatherTest[1].coord.lat )+ '</li>' +
                           '<li>Longitude: '+JSON.stringify(weatherTest[1].coord.lon )+ '</li>' +
                           '</ul>';
                           document.getElementById('weather').innerHTML = result;
                   //   })
                   }
               }
               xhr.send();
           }
           //HTTP statuses
           // 200: 'Ok'
           // 403: 'Forbidden'
           // 404: 'Not Found'
   </script>
</body>
</html>

这是我正在使用的 JSON 文件数据:

[{
   "coord":{
      "lon":-62.08,
      "lat":-31.43
   },
   "sys":{
      "message":0.3897,
      "country":"AR",
      "sunrise":1428575101,
      "sunset":1428616476
   },
   "weather":[
      {
         "id":802,
         "main":"Clouds",
         "description":"scattered clouds",
         "icon":"03d"
      }
   ],
   "base":"stations",
   "main":{
      "temp":303.364,
      "temp_min":303.364,
      "temp_max":303.364,
      "pressure":1015.65,
      "sea_level":1026.91,
      "grnd_level":1015.65,
      "humidity":42
   },
   "wind":{
      "speed":2.85,
      "deg":32.0037
   },
   "clouds":{
      "all":44
   },
   "dt":1428614645,
   "id":3837675,
   "name":"San Francisco",
   "cod":200
 },
{
   "coord":{
      "lon":-87.65,
      "lat":41.85
   },
   "sys":{
      "message":0.014,
      "country":"US",
      "sunrise":1428578344,
      "sunset":1428625502
   },
   "weather":[
      {
         "id":501,
         "main":"Rain",
         "description":"moderate rain",
         "icon":"10d"
      }
   ],
   "base":"stations",
   "main":{
      "temp":286.264,
      "temp_min":286.264,
      "temp_max":286.264,
      "pressure":991.9,
      "sea_level":1013.82,
      "grnd_level":991.9,
      "humidity":76
   },
   "wind":{
      "speed":8.25,
      "deg":202.004
   },
   "clouds":{
      "all":92
   },
   "rain":{
      "3h":4.61
   },
   "dt":1428615189,
   "id":4887398,
   "name":"Chicago",
   "cod":200
 }
]

最佳答案

正如 Todd R 所说,您只需在访问属性之前找到您实际需要的数组元素。你也不需要 JSON.stringify因为值已经是字符串或数字,可以直接放入 HTML 中。将它们包装在 stringify 调用中将导致将引号添加到字符串值中,例如。

<li>City: "San Francisco"</li>

示例代码:

xhr.onload = function(){
    const city = document.getElementById('city').value;
    if(this.status == 200){
        let cityWeathers;
        try {
            cityWeathers = JSON.parse(this.responseText);
        } catch (e) {
            // JSON not valid, show error message
        }
        const cityWeather = Array.isArray(cityWeathers) && cityWeathers.find((obj)=>obj.name === city);
        if (cityWeather) {
            const result = `<ul><li>City: ${cityWeather.name}</li>` +
                `<li>Weather: ${cityWeather.weather[0].description}</li>` + 
                `<li>Latitude: ${cityWeather.coord.lat}</li>` +
                `<li>Longitude: ${cityWeather.coord.lon}</li></ul>`;

            document.getElementById('weather').innerHTML = result
        }
    }
}

关于javascript - 如何根据输入值呈现 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58457085/

相关文章:

javascript - jQuery datepicker future 一天的值

json - json 字符串上的 Bash 元组

javascript - JSON解析错误: Unexpected identifier "RCTWebSocketModule"

java - Jersey 和 Guice 以及漂亮的 JSON

javascript - JS defineProperty 和原型(prototype)

javascript - 应用不同的复选框过滤器来显示/隐藏 div

javascript - .remove() 在 IE 和 Firefox 中不起作用

javascript - Paypal 期望传递一个订单 ID

android - 如何在Flutter中获取复杂的Json对象?

java - 如何在 json 文件中编辑和添加嵌套数据?