更新待办事项列表,而无需在express nodejs应用程序中刷新页面 [英] Update the todo list without refreshing the page in express nodejs app

查看:91
本文介绍了更新待办事项列表,而无需在express nodejs应用程序中刷新页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是express nodejs应用程序的新手.我想做一个待办事项清单.到目前为止是这样.我的问题是,当我添加待办事项时,由于它会重新加载页面,因此需要花费一些时间来显示更改.如何在不重新加载页面的情况下实时查看更改.预先感谢.

I am a newbee to the express nodejs applications. I want to make a todo list. This is how it looks so far. My question is when I add a todo, it takes some time to show the change since it reloads the page. How can I see the change in realtime without reloading the page. Thanks in advance.

tasks.jade

 h1= title

  .list
    .item.add-task
      div.action
        form(action='/tasks', method='post', id='12345')
          input(type='hidden', value='true', name='all_done')
          input(type='hidden', value=locals._csrf, name='_csrf')
          input(type='submit', class='btn btn-success btn-xs', value='all done')
      form(action='/tasks', method='post')
        input(type='hidden', value=locals._csrf, name='_csrf')
        div.name
          input(type='text', name='name', placeholder='Add a new task')
        div.delete
          input.btn.btn-primary.btn-sm(type="submit", value='add')
    if (tasks.length === 0)
      | No tasks.
    each task, index in tasks
      .item
        div.action
          form(action='/tasks/#{task._id}', method='post')
            input(type='hidden', value=task._id.toString(), name='id')
            input(type='hidden', value='true', name='completed')
            input(type='hidden', value=locals._csrf, name='_csrf')
            input(type='submit', class='btn btn-success btn-xs task-done', value='done')
        div.num
          span=index+1
            |. 
        div.name
          span.name=task.name + ' (Created at: ' + moment(task.createTime).format("YYYY/MM/DD") + ')'
          //- no support for DELETE method in forms
          //- http://amundsen.com/examples/put-delete-forms/
          //- so do XHR request instead from public/javascripts/main.js
        div.delete
          a(class='btn btn-danger btn-xs task-delete', data-task-id=task._id.toString(), data-csrf=locals._csrf) delete

app.js

app.get('/', routes.index);
app.get('/tasks', tasks.list);
app.post('/tasks', tasks.markAllCompleted)
app.post('/tasks', tasks.add);
app.post('/tasks/:task_id', tasks.markCompleted);
app.delete('/tasks/:task_id', tasks.del);
app.get('/tasks/completed', tasks.completed);

tasks.js

exports.add = function(req, res, next){
  if (!req.body || !req.body.name) return next(new Error('No data provided.'));
  req.db.tasks.save({
    name: req.body.name,
    createTime: new Date(),
    completed: false
  }, function(error, task){
    if (error) return next(error);
    if (!task) return next(new Error('Failed to save.'));
    console.info('Added %s with id=%s', task.name, task._id);
    res.redirect('/tasks');
  })
};

推荐答案

ExpressJS是服务器端框架.这意味着当浏览器请求视图时,它将提供视图.为了防止浏览器在与页面交互时刷新整个页面,您需要查看客户端框架.

ExpressJS is a server-side framework. That means it serves up views when a browser makes requests for them. In order to prevent the browser from making a full page refresh when interacting with the page you need to look into a client-side framework.

我强烈建议您查看 AngularJS ,但这对于初学者而言可能是一个令人生畏的框架.如果您还没有的话,我一定会先学习 JQuery .许多其他框架要么直接建立在JQuery之上,要么模仿JQuery所采用的某些模式.我将首先关注JQuery,然后再升级到诸如AngularJS之类的高级框架.

I highly recommend taking a look at AngularJS, but that can be a daunting framework for a beginner. I would definitely first learn JQuery if you haven't already. Many other frameworks either build on top of JQuery directly or mimic some of the patterns employed by JQuery. I would focus on JQuery first and then graduate to a higher-level framework like AngularJS or something similar.

以下是使用JQuery劫持表单提交的示例:

Here is an example of hijacking a form submit with JQuery:

<script type="text/javascript">
  $('#myForm').on('submit', function (event) {
    event.preventDefault(); // Stop the form from causing a page refresh.
    var data = {
      username: $('#username').val(),
      password: $('#password').val()
    };
    $.ajax({
      url: 'http://localhost/my/url',
      data: data,
      method: 'POST'
    }).then(function (response) {
      // Do stuff with the response, like add it to the page dynamically.
      $('body').append(response);
    }).catch(function (err) {
      console.error(err);
    });
  });
</script>

如果您将该脚本标记放在页面底部,紧接在</body> 标记之前,它将劫持ID为 myForm 的表单并为 submit 事件附加事件处理程序.提交表单后,事件处理程序将首先触发.处理程序 event.preventDefault()的第一行告诉浏览器不要执行默认的提交行为并刷新页面.然后,我们创建一个 data 对象,以存储我们感兴趣的表单域的值.在本示例中,我使用ID为"username"的文本输入和ID为"username"的密码输入密码".请注意,传递给 $()的字符串看起来很像CSS选择器,这就是这个主意:)

If you put that script tag at the bottom of a page, just before the closing </body> tag, it will hijack a form with the ID myForm and attach an event handler for the submit event. When the form is submitted the event handler will fire first. The first line of the handler event.preventDefault() tells the browser not to perform the default submit behavior and refresh the page. Then after that we create a data object to store the values of the form fields that we are interested in. In this example I use a text input with the ID "username" and a password input with the ID "password". Notice how the string you pass to $() looks a lot like a CSS selector, that's the idea :)

一旦我们有要发布到服务器的数据,我们就会发出一个 AJAX 请求,数据,我们将处理响应,如果发现任何错误,则将其捕获.发生此AJAX请求时不会刷新页面:)

Once we have the data we want to post to the server, we make an AJAX request with the data and we handle the response, or catch any errors if they occur. This AJAX request happens without refreshing the page :)

该脚本必须在页面底部的原因是,元素需要在运行之前加载.通过JQuery,可以确保在运行脚本之前准备好整个文档.

The reason this script has to be at the bottom of a page is because the elements need to be loaded before it runs. JQuery makes it possible to ensure that the entire document is ready before running scripts.

$(document).on('ready', function (event) {
  // This code won't run until the whole page is ready.
});

如果将代码放置在该事件处理程序中,则可以将脚本标记放在页面上的任何位置,甚至可以放置在< head> 中.JQuery为该事件处理程序提供了快捷方式,因为它已被大量使用.

If you place your code in that event handler then you can put the script tag anywhere on the page, even in the <head>. JQuery offers a shortcut for that event handler because it's used a lot.

$(function (event) {
  // This is sugar for $(document).on('ready', function () { ... });
});

这篇关于更新待办事项列表,而无需在express nodejs应用程序中刷新页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆