简体   繁体   中英

Best practise for update DOM after Ajax call

I want to know what's the best practise for updating DOM after an Ajax call.

For example, imagine we have a list of users and we can add a user with a form which make an Ajax call to insert the user. After the form is submitted and the user added in database, the DOM is edited to add HTML without refreshing the page (with the Ajax success event).

I see two possibility to make this :

  1. Make an Ajax call who add the user in db and return all the DOM structure with html tag, etc.

  2. Make an Ajax who add the user in db and return all the data of an user and create the DOM element in Javascript

What'is the best way to do it (or another way) ?

You can add elements to the DOM with document.createElement() . Then use the innerHTML property to add content to the element. Finally append the element to another with .appendChild() .

There is no better way between the two options. You can either prepare your HTML structure in the backend and import the written HTML and directly append it with JavaScript or create the elements frontend in JavaScript.

Here are the main advantages to using the latter:

  • it's easier to debug JavaScript than PHP (PHP files targetted by AJAX calls are quite hard to debug and to maintain).

  • returning an object with AJAX instead of an HTML string is easier to use and more maintainable. You can have an API to handle the data. PHP only returns a JSON object.

  • if JavaScript handles the creation of elements, you can save those in variables. Sometimes, I find it useful to save an HTMLElement in a JavaScript variable so I can later access it to change its properties without having to go through selectors ( querySelector() and others).

I would go with the second option

  • Make an Ajax who add the user in db and return all the data of an user and create the DOM element in Javascript

Breaking it down like so to improve on readability and maintenance

  • Add action to AJAX that is linked to a function on the backend, (ie PHP, Python) that does the DB update and more.

  • Create the Element structures in Javascript (You can maintenance uniformity with other structures on your page). And wrap it in a function.

     document.body.onload = addElement; function addElement ($newuser) { // create a new div element that would contain user record var newDiv = document.createElement("div"); // and give it some content var newContent = document.createTextNode($newuser); // add the text node to the newly created div newDiv.appendChild(newContent); // add the newly created element and its content into the DOM var currentDiv = document.getElementById("user-container"); document.body.insertBefore(newDiv, currentDiv); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM