Changing the variable name during a repeat loop in Javascript

Asked

Viewed 356 times

2

I want to make an indefinite number of ajax requests, according to the number of urls passed as parameter, I just need to know how to increment the (name) of the variable so that the answer does not overlap with the previous one.

Each request will fetch a different html content or json object and insert them into different elements of the document, without changing the variable all elements are incremented with the last loop response. Obs, putting the third argument 'false', in the open() method; right, but gives an alert in the console saying that it is not a good practice

[Deprecation] Synchronous Xmlhttprequest on the main thread is deprecated because of its detrimental effects to the end user’s Experience.

Example of what I’m looking for:

With each iteration I want the variable name to change:

var a = new XHtmlHTTPrequest();

In the next iteration:

var b = new XHtmlHTTPrequest();

2 answers

8


Here’s an example with the Starwars API :)

The important ideas are:

  • passes the element to be iterated to a new context/scope, so that variable is stored inside the function.

  • chain ajax and function to be applied to elements passing the final function as callback to ajax to call. This function already takes saved the element as described above.

function ajax(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url);
  xhr.onload = function() {
    if (xhr.status === 200) {
      callback(JSON.parse(xhr.responseText));
    } else {
      alert('O ajax falhou! ' + xhr.status);
    }
  };
  xhr.send();
}

function adicionarNomeDepois(el) {
  var label = el.querySelector('label');
  label.innerHTML = 'A carregar...';
  return function(data) {
    label.innerHTML = data.name;
    el.querySelector('p').innerHTML = data.starship_class;
  }
}

var base = 'https://swapi.co/api/starships/';
var divs = document.querySelectorAll('[data-nrnave]');
for (var i = 0; i < divs.length; i++) {
  var el = divs[i];
  var url = base + el.dataset.nrnave;
  ajax(url, adicionarNomeDepois(el));
}
div {
  border: 1px solid #666;
  padding: 10px;
}

label {
  font-weight: bold;
}
<div data-nrnave="15">
  <label></label>
  <p></p>
</div>
<div data-nrnave="5">
  <label></label>
  <p></p>
</div>
<div data-nrnave="9">
  <label></label>
  <p></p>
</div>
<div data-nrnave="10">
  <label></label>
  <p></p>
</div>
<div data-nrnave="11">
  <label></label>
  <p></p>
</div>
<div data-nrnave="12">
  <label></label>
  <p></p>
</div>

  • 1

    callback and asynchronous is always a good way +1. PS: Congratulations on 100k, synonymous with commitment, the community just has to thank you.

  • 1

    @Thank you Guilhermenascimento! And you walk there too :)

  • 1

    -1 for not using Yoda Conditions with Star Wars API :D

  • @bfavaretto haha :)

  • I had not tried with callback yet, in fact the scope of the function will isolate the variable and solve my problem. however the doubt remains it is possible to auto increment the name of a variable?

  • @Rodrigoa.Santos you can, but it’s not the best solution. You can create an object and then go on doing obj['div-' + i] = algo..., but in this case it is not so useful.

  • @Rodrigoa.Santos could even use one Map (new technology) that accepts as key the DOM element itself.

  • Too bad the Star Wars API doesn’t have images!!

Show 3 more comments

4

Instead of changing the variable you could use a list, improving control over the code.

var a = [];
for (var i = 0; i < 4  ; i++) {
    var x = new XMLHttpRequest();
    a.push(x);
}

console.log(a);
  • Opá did not know that this was possible, should solve my problem!

  • apparently not for sure!

  • I fixed the code, to include an item in the array you must use the . push method

  • Good! gave me a light here, but I will have to make two loops, one to create the array and one to execute the ajax requests!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.