0

I'm using nodejs to develop a website that extract data from an API using ajax requests. I use templates, .hbs files (index.hbs, area.hbs etc.). My problem is that I want to make a navbar (with text links), but since I use templates its not that easy. I need to use ajax. I have made ​​all the necessary routes, but I need help with the ajax request on the links. I have searched the internet for an answer, and tried a lot of different solutions, but nothing seems to solve my problem.

My navbar code:

<div id="navbar">
     <ul>
          <li>Companies</li>
          <li>Area</li>
     </ul>
</div>

Server.js route code:

app.get('/area', routes.goToArea);

Routes.js code:

goToArea: function (req, res) {
            res.render('area');
        }

I think something along those lines could work:

var url = "/area";
        function area() {
            $.ajax({
                url: url,
                type: 'GET',

Any help would be greatly appreciated!

4

2 回答 2

0

这是您绑定click事件并发出ajax请求的方式

$(document).ready(function () {
    $('.navbar a').click(function () {
        $.ajax({
            'type': 'get',
            'url': '/area',
            'success': function (data) {
                // use the data
            }
        })
    })
})
于 2013-08-14T07:44:05.247 回答
0

从概念上讲,我会创建在全局布局内呈现的部分布局(或 html 部分)。这个“部分”应该代表一个区域。

我还会在代表区域标识符的 html(id 或数据属性)中有一个变量。那么你可以要求类似的东西

http://myserver.com/area/tab1或者

http://myserver.com/?area=tab1

(取决于您希望如何构建代码/路由。

然后,您应该通过 ajax 和“成功”请求该部分,然后将其插入 Dom。

这里的文档解释了如何组装 ajax 调用:

http://api.jquery.com/jQuery.ajax/

这是一本很好的读物,可能也有帮助:

Express.js hbs 模块 - 从 .hbs 文件注册部分

于 2013-08-14T07:45:03.770 回答