user3826891 user3826891 - 23 days ago 6
Javascript Question

Shorten js script using $.each function

I have the following .js code which reads a json file to update the values in the html every minute.

$(document).ready(updateData);
function updateData() {
$.ajaxSetup({ cache: false });
$.getJSON("data/data.json", function(result){
$('#id1').empty();
$('#id1').append(result.id1);
$('#id2').empty();
$('#id2').append(result.id2);
$('#id3').empty();
$('#id3').append(result.id3);
$('#id4').empty();
$('#id4').append(result.id4);
$('#id5').empty();
$('#id5').append(result.id5);
$('#id6').empty();
$('#id6').append(result.id6);
$('#id7').empty();
$('#id7').append(result.id7);
$('#id8').empty();
$('#id8').append(result.id8);
$('#id9').empty();
$('#id9').append(result.id9);
});
setTimeout(updateData, 60000);
}


Can this be rewritten in a shorter way using the $.each() function?

Answer

It can be improved using a simple for loop:

$.ajaxSetup({ cache: false }); // 1
$(document).ready(updateData);

function updateData() {
  $.getJSON("data/data.json", function(result) {
    for (var i = 1; i<= 9; i++) {
      $('#id' + i).empty().append(result['id' + i]); // 2
    }

    setTimeout(updateData, 60000); // 3
  });
}

However, accessing the DOM by concatenated IDs does not look good.
For example, you can try to implement it using CSS classes and data-attributes.

Some minor improvements:

  1. ajaxSetup can only be initialized once, you don't need to call it every time.
  2. You probably don't need to empty() and append() at the same time. If it is a text, you can simply use .text(), or .html() for HTML.
  3. It is a good idea to call setTimeout in your getJSON callback so that it updates data in 60 seconds after a previous request is completed, better in .always() handler. Imagine that one of your clients has very slow connection and it takes more than 60 seconds to load this JSON. It will lead to unexpected results.