【问题标题】:How to update JSON query / data after new user input?新用户输入后如何更新 JSON 查询/数据?
【发布时间】:2021-05-11 12:14:06
【问题描述】:

我正在创建一个每 5 秒更新一次的天气仪表板。我希望用户能够更改目标城市,并使用新数据更新仪表板。 问题是每次他们输入一个新城市时,以前的数据都会保留下来,并且似乎在循环用户迄今为止所做的所有输入。

我希望在用户输入新城市后更新数据,而不是添加。这是我的代码:

window.onload = function() {
    const api_key = "c7eedc2fa8594d69aa6122025212904";
    const inputCity = document.getElementById("inputCity");
    const getCity = document.querySelector("form");

    getCity.addEventListener("submit", e => {
        // Prevent the form from submission
        e.preventDefault();
        var inputVal = inputCity.value;
        var api_url = "http://api.weatherapi.com/v1/forecast.json?key=" + api_key + "&q=" + inputVal + "&days=3&aqi=no&alerts=no";
        // Get the dataset
        function refreshData() {
            fetch(api_url).then(response => {
                response.json().then(json => {
                        var dataset = json;
                        var output = formatResponse(dataset);
                    })
                    // Catch error - for example, the user doesn't input a valid city / postcode / country
                    .catch(error => console.log("not ok")); // TO BE IMPROVED
            })

        }

        refreshData(); // Display the dashboard immediately

        setInterval(refreshData, 5000); // And then refresh the dashboard every X milliseconds


    });

    function formatResponse(dataset) {

        console.log(dataset);

        // Current temp
        var currentTemp = [dataset.current.temp_c];
        console.log(currentTemp);
        document.getElementById("currentTempDsp").innerHTML = currentTemp + "°";

        // Current state icon
        var currentIcon = [dataset.current.condition.icon];
        console.log(currentIcon);
        document.getElementById("iconDsp").src = "http://" + currentIcon;

        // Current state text
        var currentText = [dataset.current.condition.text];
        console.log(currentText[0]);
        document.getElementById("currentStateDsp").innerHTML = currentText;

    }


}
        <form id="getCity" class="search">
            <label id="labelCity">Search for a city...</label></br>
            <input type="text" id="inputCity" class="inputCity" placeholder="Type city name here...">
            <button id="submitCity" type="submit" class="submitCity"><i class="fas fa-search"></i>Submit</button>
        </form>
            <div class="state">
                <h2 id="currentTempDsp"></h2>
                <img id="iconDsp"/>
                <span id="currentStateDsp"></span>
            </div>

        </div>
        
    </div>

【问题讨论】:

  • 您必须在变量中存储对当前间隔的引用,然后在设置新间隔之前使用clearInterval() 清除。
  • @esqew 谢谢,我试过这样做,但不幸的是它不起作用:(
  • 您能否更具体地说明为什么链接副本中的答案不符合您的要求(错误消息、预期与实际行为)?
  • @esqew 它没有改变任何东西,因为我遇到了同样的问题。我将设置的间隔存储在一个变量(间隔)中并添加了 clearInterval(interval);在提交事件侦听器中到处都是,但什么都没有。您能否提供一些代码说明您将如何做到这一点?

标签: javascript json user-input json-query


【解决方案1】:

当您使用setInterval() 创建间隔时,它会继续执行,直到页面重新加载、导航离开或使用clearInterval() 明确清除。简单地设置更多间隔不会阻止任何以前的间隔触发。

使用全局范围的变量来存储 setInterval() 的返回值 - 检查它是否在提交事件处理程序的开头设置,如果是则清除它。

如何完成此操作的简化示例:

const locations = [{
  temp: 73,
  conditions: 'Sunny'
}, {
  temp: 22,
  conditions: 'Mostly Cloudy'
}];

var currentInterval = null;

const updateTemp = locationData => {
  document.querySelector(".number").innerText = locationData.temp;
  document.querySelector(".conditions").innerText = locationData.conditions;
  console.log(`updated interface with temperature (${locationData.temp}) and conditions (${locationData.conditions}) data`);
}

[...document.querySelectorAll('.add-location')].forEach(button => {
  button.addEventListener('click', (e) => {
    // clear the interval
    if (currentInterval) {
      clearInterval(currentInterval);
      currentInterval = null;
      console.log('cleared currentInterval');
    }
    updateTemp(locations[parseInt(e.srcElement.dataset.loc)]);
    currentInterval = setInterval(function () {
      updateTemp(locations[parseInt(e.srcElement.dataset.loc)]);
    }, 2500);
  });
});
* {
  font-family: sans-serif;
}

.temp {
  font-size: 2em;
}

.conditions {
  font-style: italic;
}
<div class="temp">
  <span class="number">--</span>
  <span class="deg">&deg;</span>
</div>
<div class="conditions">--</div>
<div>
  <button class="add-location" data-loc="0">Add location 0</button>
  <button class="add-location" data-loc="1">Add location 1</button>
</div>

【讨论】:

  • 成功了!!!!!!非常聪明/简单的方法。希望我不是这样的菜鸟:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多