【问题标题】:Avoid loading XHR data each time避免每次都加载 XHR 数据
【发布时间】:2021-12-16 06:03:26
【问题描述】:

我想创建一个包含两个字段的表单。一个是起点站,另一个是终点站。电台存储在一个 JSON 文件 {[],[],[]} 这个 json 文件大小约为 400KB。我只想初始化一次站并将它们用于两个输入字段。但我不能那样做。所以我重写了它,以便在您关注输入字段时立即加载 JSON。这很愚蠢。我会很高兴得到帮助。这是我目前的结构:

app.js

// load own suggestion script
import suggestion from './suggestion';

document.getElementById('from').addEventListener('focus', function() {
    suggestion.start('from')
});

document.getElementById('to').addEventListener('focus', function() {
    suggestion.start('to')
});

suggestion.js

export default {
    stations: [],
    formSelector: '',
    url: 'http://localhost:8090/api.php',
    getData() {
        fetch(this.url)
            .then(res => res.json())
            .then(data => { 
                // call the autocomplete function and pass the stationData               
                this.autocomplete(document.getElementById(this.formSelector), data)
            })
            .catch(err => {
                console.log(err)
            });
    },
    autocomplete(inp, arr) {
        // some code ... this code fetch the input value and iterate the stations object and create a suggestionlist. I have shortened it for this question.
    },
    start(selector) {
        this.formSelector = selector;
        this.getData();
    }
}

html

<span>from</span>
<input id="from" type="text" placeholder="Station from">

<span>to</span>
<input id="to" type="text" placeholder="Station to">

【问题讨论】:

  • 也许pagination 或者只获取输入了第一个字母的东西
  • @mplungjan 谢谢!您可能可以更改结构中的某些内容,以便它只加载一次数据。然而,这就是我遇到承诺“问题”的地方。

标签: javascript promise xmlhttprequest fetch autosuggest


【解决方案1】:

下面是怎么回事?
是你想做的吗?

getData() {
    if( this.stations ) {
        this.autocomplete(document.getElementById(this.formSelector), this.stations);
    } else {
        fetch(this.url)
            .then(res => res.json())
            .then(data => { 
                // call the autocomplete function and pass the stationData               
                this.stations = data;
                this.autocomplete(document.getElementById(this.formSelector), this.stations);                    
            })
            .catch(err => {
                console.log(err)
            });
    }
},

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-13
    • 2019-06-27
    • 2011-01-26
    • 2023-03-22
    • 1970-01-01
    • 2020-08-25
    • 2021-03-21
    • 2014-10-31
    相关资源
    最近更新 更多