按钮 onclick 获取调用 getIndex() 的请求

Button onclick get request to invoke getIndex()

我有一个按钮,它应该执行对“/index”的获取请求。 然后我的页面应该通过路由方法调用 getIndex,它应该呈现 index.html.

    <div>
        <script> function goToHome(){ 
            $.get("/index");
        }
        </script>

        <button type="button" onclick="goToHome()">
            Go to the dashboard!
        </button>   
    </div>

router.get('/index', Routemethods.getIndex);

exports.getIndex = function(req, res){
    res.render('index.html');
}

但是,已发出请求,并且正在调用 getindex(记录以查看是否调用)。问题是我的页面没有重新加载到 index.html。我究竟做错了什么?我使用 href 让它工作,但不是那种方法的忠实拥护者。

您没有指定这是浏览器上的节点还是 jquery。这似乎是一个 ajax 调用,而不是导航。

   <script> function goToHome(){ 
        $.get("/index");
    }
    </script>

这将使您的浏览器请求页面

   function goToHome(){
         window.location.href = '/index'; // this might need tweaking based on your servers setup, paths, etc
   }

但如前所述,您可以使用 link 和正确的 href 来完成此操作。除非有充分的理由,否则您不应该将其卸载到按钮和 js。您正在使用更多内存并使导航依赖于 js。