按钮调用函数,而无需更改URL或重新加载整个页面

Button to call function without changing URL or reloading entire page?

本文关键字:加载 新加载 函数 调用 URL 按钮      更新时间:2023-09-26

现在我有2个按钮,一个调用函数做某事,另一个显示信息到页面上。

router.get('/run-func', function(res, req, next) {
    //call function
    res.render('index');
};
router.get('/get-data', function(res, req, next) {
    //get info from db...
    res.render('index', {items: tempArray});
};

每次点击一个按钮,它将我发送到另一个url,但显示索引页:

http://localhost: 3000/run-func

http://localhost: 3000/获取数据

问题是每次我单击run- function时,它都会重新加载页面,并且从get-data显示的数据消失。有没有办法使这些按钮不加载不同的url ?

HTML是使用手柄完成的,下面是get-data:

<div class="get">
    <h3>Get Data</h3>
    <a href="/get-data">LOAD DATA</a>
    <div>
        {{# each items }}
            <article class="item">
                <div>id: {{ this._id }}</div>
                <div>prop: {{ this.prop }}</div>
            </article>
        {{/each}}
    </div>
</div>

try this

function processAjaxData(response, urlPath){
     document.getElementById("content").innerHTML = response.html;
     document.title = response.pageTitle;
     window.history.pushState({"html":response.html,"pageTitle":response.pageTitle},"", urlPath);
 }

然后可以使用window。Onpopstate用于检测后退/前进按钮导航:

window.onpopstate = function(e){
    if(e.state){
        document.getElementById("content").innerHTML = e.state.html;
        document.title = e.state.pageTitle;
    }
};