首页 > 解决方案 > 如何执行函数来更新 json 源

问题描述

我有一张传单地图,显示了来自 Json 源的一些天气数据。我已经有一个通过 setInterval 函数每 x 分钟更新一次数据的函数。

    setTimeout(function () {
        refreshId = setInterval(function () {

            $.ajax({
                method: 'get',
                dataType: 'text',
                url: 'myURLfile.json',
                success: function (data) {
                    if (data) {
                        markers = [];
                        var withoutMarkers = data.slice(10);
                        markers = JSON.parse(withoutMarkers);
                        //console.log(markers);

                        replaceMarkers(currentFactor);

                    }
                },
                error: function (err) {
                    console.error('there is not date for today.', err)
                }
            })
        }, 300000);
    },10000)

}

我现在要做的是将此功能分配给一个按钮以手动执行刷新功能。就像是

        L.easyButton( 'fas fa-cloud-sun-rain', function(){
            myfunction()
        }, 'Refresh', {
            position: 'topright'
        })

但我不明白我必须调用什么才能做到这一点。

标签: javascriptjsonajaxleaflet

解决方案


将您的获取代码排除在外,并在您的按钮定义setInterval中使用您新制作的功能。setInterval

就像是

function fetchData() {
    $.ajax({
        method: 'get',
        dataType: 'text',
        url: 'myURLfile.json',
        success: function (data) {
            if (data) {
                markers = [];
                var withoutMarkers = data.slice(10);
                markers = JSON.parse(withoutMarkers);
                //console.log(markers);

                replaceMarkers(currentFactor);

            }
        },
        error: function (err) {
            console.error('there is not date for today.', err)
        }
    });
}

// setup your interval
setInterval(fetchData, 300000);

// setup your button
L.easyButton( 'fas fa-cloud-sun-rain', fetchData, 'Condizioni', {
    position: 'topright'
})

推荐阅读