Update the todo list without refreshing the page in express nodejs app

前端 未结 2 1059
囚心锁ツ
囚心锁ツ 2021-02-06 19:53

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 chang

2条回答
  •  别那么骄傲
    2021-02-06 20:32

    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.

    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.

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

    
    

    If you put that script tag at the bottom of a page, just before the closing 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 :)

    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 :)

    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.
    });
    

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

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

提交回复
热议问题