Home > Software design >  How to write this code better and to be similar? Javascript
How to write this code better and to be similar? Javascript

Time:01-28

Hi i made some code using ajax and i was playing, and i don't know how to reduce the code to keep it useful, is there any way? i have used this .done multiple times and i could have surely once If you can write me a similar code but to be reduced? i don't even know if this is the best way to use ajax? i don't even know if this is the best way to use ajax? i don't even know if this is the best way to use ajax?

var tbody = $('.tbody');

$('.item').on('click', function() {
  $(this).addClass('active').siblings().removeClass('active');
});

$('li a').on('click', function(e) {
  e.preventDefault();
  var link = $(this).attr('href');
  if (link == "books") {
    $.ajax({
      url : "https://mysafeinfo.com/api/data?list=bestnovels1&format=json&case=default&token=XH5nFfa1MsMqUNaZ3716yRM2WaJjIT6L",
      dataType : "json"
    })
    .done(function (res) {
      $('.page-header').html(link);
      var text1 = '';
      for(prop in res[0]) {
        text1  = '<th>' prop '</th>'
      }
      thead.html(text1);
      var text = '';
      for (var i = 0; i < res.length; i  ) {
        text  = '<tr>';
      for(prop in res[i]) {
        text  = '<td>' res[i][prop] '</td>'
      }
        text  = '</tr>';
      }
      tbody.html(text);
      
    });
  }else if(link == "novels") {
    $.ajax({
      url : "https://mysafeinfo.com/api/data?list=bestnovels7&format=json&case=default&token=XH5nFfa1MsMqUNaZ3716yRM2WaJjIT6L",
      dataType : "json"
    })
    .done(function (res) {
      $('.page-header').html(link);
      var text1 = '';
      for(prop in res[0]) {
        text1  = '<th>' prop '</th>'
      }
      thead.html(text1);
      var text = '';
      for (var i = 0; i < res.length; i  ) {
        text  = '<tr>';
      for(prop in res[i]) {
        text  = '<td>' res[i][prop] '</td>'
      }
        text  = '</tr>';
      }
      tbody.html(text);
      
    });

  }else if(link == "actors") {
    $.ajax({
      url : "https://mysafeinfo.com/api/data?list=bestactors1&format=json&case=default&token=XH5nFfa1MsMqUNaZ3716yRM2WaJjIT6L",
      dataType : "json"
    })
    .done(function (res) {
      $('.page-header').html(link);
      var text1 = '';
      for(prop in res[0]) {
        text1  = '<th>' prop '</th>'
      }
      thead.html(text1);
      var text = '';
      for (var i = 0; i < res.length; i  ) {
        text  = '<tr>';
      for(prop in res[i]) {
        text  = '<td>' res[i][prop] '</td>'
      }
        text  = '</tr>';
      }
      tbody.html(text);
      
    });
  }

})

CodePudding user response:

not so hard to do...

const urls =
  { books  : 'https://mysafeinfo.com/api/data?list=bestnovels7&format=json&case=default&token=XH5nFfa1MsMqUNaZ3716yRM2WaJjIT6L'
  , novels : 'https://mysafeinfo.com/api/data?list=bestnovels1&format=json&case=default&token=XH5nFfa1MsMqUNaZ3716yRM2WaJjIT6L'
  , actors : 'https://mysafeinfo.com/api/data?list=bestactors1&format=json&case=default&token=XH5nFfa1MsMqUNaZ3716yRM2WaJjIT6L'
  }
mySelect.oninput =_=>
  {
  myTable.innerHTML = '' // clear table
 
  fetch( urls[mySelect.value] )
  .then(resp=> resp.json() )
  .then(data=>
    {
    let Names = Object.keys(data[0])
    data.forEach((row,i) => 
      {
      let newRow = myTable.insertRow()
      Names.forEach(name => newRow.insertCell().textContent = row[name])
      })
    let newRowHead = myTable.createTHead().insertRow()
    Names.forEach(name => newRowHead.insertCell().outerHTML = `<th>${name}</th>` )       
    })
  }
table {
  font             : 14px Arial, Helvetica, sans-serif;
  white-space      : nowrap;
  border-collapse  : separate;
  border-spacing   : 1px;
  background-color : darkblue;
  margin           : 1em 0 0 0; 
  }
td { padding: .3em .6em; background-color : whitesmoke;     } 
th { padding: .3em .6em; background-color : lightsteelblue; }
<select id="mySelect">
  <option value="" selected disabled >pick one...</option>
  <option value="books" >books</option>
  <option value="novels" >novels</option>
  <option value="actors">actors</option>
</select>

<table id="myTable"></table>

CodePudding user response:

Since your done functions are identical you can move the code to single function and run it inside each .done, like:

.done(res => buildTable(link, res));

going further you can see that every Ajax is the same (almost). Only url is different, so you can write something like:

function loadTable(link, url) {
  $.ajax({
    url: url,
    dataType: "json"
  })
    .done(function (res) {
      $('.page-header').html(link);
      var text1 = '';
      for (prop in res[0]) {
        text1  = '<th>'   prop   '</th>'
      }
      thead.html(text1);
      var text = '';
      for (var i = 0; i < res.length; i  ) {
        text  = '<tr>';
        for (prop in res[i]) {
          text  = '<td>'   res[i][prop]   '</td>'
        }
        text  = '</tr>';
      }
      tbody.html(text);
    });
}

$('li a').on('click', function(e) {
  e.preventDefault();
  const link = $(this).attr('href');
  const links = {
    books: "https://mysafeinfo.com/api/data?list=bestnovels1&format=json&case=default&token=XH5nFfa1MsMqUNaZ3716yRM2WaJjIT6L",
    novels: "https://mysafeinfo.com/api/data?list=bestnovels7&format=json&case=default&token=XH5nFfa1MsMqUNaZ3716yRM2WaJjIT6L",
    actors: "https://mysafeinfo.com/api/data?list=bestactors1&format=json&case=default&token=XH5nFfa1MsMqUNaZ3716yRM2WaJjIT6L",
  }
  loadTable(link, links[link]);
}

The urls are also similar so you can put only differences to to the map:

const links = {
    books: "novels1",
    novels: "novels7",
    actors: "actors1",
  }
loadTable(link, `https://mysafeinfo.com/api/data?list=best${links[link]}&format=json&case=default&token=XH5nFfa1MsMqUNaZ3716yRM2WaJjIT6L`);
  •  Tags:  
  • Related