How to rename the variable during a loop in JavaScript

2

I want to do an indefinite number of ajax requests, depending on the number of pass urls as a parameter, I only need to know how to increment the (name) of the variable so that the response does not overlap with the previous one.

Each request will fetch a different html or json object and insert them into different elements of the document, without changing the variable all elements are incremented with the last response of the loop. Obs, putting the third argument 'false', in the open () method; of course, but an alert on the console saying 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:

At each iteration I want the variable name to change:

var a = new XHtmlHTTPrequest();

In the next iteration:

var b = new XHtmlHTTPrequest();
    
asked by anonymous 25.09.2017 / 15:51

2 answers

8

Here is an example with the StarWars API:)

The important ideas are:

  • chain ajax and the function to apply to the elements passing the final function as callback for the ajax call. This function already takes 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>
    
25.09.2017 / 19:33
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);
    
25.09.2017 / 16:04