2020年12月25日星期五

Is it possible to optimize the code, advice is needed (JS, AJAX)

I'm not sure if the code I wrote is the best one, or even close to it.
I need to display items by category, something like that:
function that calls getDoctorsGroup on the screenshot
screen

  • category
    • item 1
    • itme 2
    • ...
  • category2
    • item 1
    • itme 2
    • ...

My code:

    function getDoctorsGroup(id, title) {      let xhttp = new XMLHttpRequest();      let doctorsArr = [];        xhttp.onreadystatechange = function () {        if (this.readyState == 4 && this.status == 200) {          doctorsArr = JSON.parse(this.responseText);          let html = "";                    html += '<div class="members-group">';          html += `<span class="text">${title}</span>`;          doctorsArr.forEach(doctor => {            if(doctor.category == id) {              html += `<h3 class="member-name truncate-text-item">${doctor.name}</h3>`;              html += `<p class="member-job truncate-text-item">${doctor.job}</p>`;            }          })            // Insert group into list          const container = document.querySelector(".chat-list_members");          container.insertAdjacentHTML("beforeend", html);        }      }      xhttp.open(        "POST",        "http://localhost/yourdomen/api/readDoctors.php",        true      );      xhttp.send();    }  
https://stackoverflow.com/questions/65453331/is-it-possible-to-optimize-the-code-advice-is-needed-js-ajax December 26, 2020 at 11:02AM

没有评论:

发表评论