How to make a request... Xmlhttprequest with array

Asked

Viewed 68 times

0

following code:

let info = new Array()

info[0] = 'index.php'
info[1] = 'portifolio.php'
info[2] = 'nn'

let url = ['https://xraros.000webhostapp.com/']
let proxy = 'https://cors-anywhere.herokuapp.com/';
let ajax = new XMLHttpRequest();

    for(let i = 0; i < info.length; i++){
    ajax.onreadystatechange = () => {
        if(ajax.readyState == 4){
            if(ajax.status == 200){

                console.log('achou')          

            }else{
                console.log('nao achou')

            }            
        }
    }
    ajax.open('GET',proxy+url+info[i],true);
    ajax.send()
}

I want to know why the other answers do not appear on the console and only one that is:

GET https://cors-anywhere.herokuapp.com/https://xraros.000webhostapp.com/nn 404 (Not Found)
(anonymous) @ teste.html:40
teste.html:32 nao achou

have to test the index values of the array and show for each one if found or did not find? It’s been a long time since I’ve had this doubt..., I’ve just tried it like the code above. Thank you very much.

1 answer

1


Move the let ajax = new XMLHttpRequest() into your noose for. You should create an object for each iteration, the way you are doing, you are canceling the previous request by invoking the method send in the same object:

let info = new Array();

info[0] = 'index.php';
info[1] = 'portifolio.php';
info[2] = 'nn';

let url = 'https://xraros.000webhostapp.com/';
let proxy = 'https://cors-anywhere.herokuapp.com/';

for (let i = 0; i < info.length; i++) {
    let ajax = new XMLHttpRequest();
    
    ajax.onreadystatechange = () => {
        if (ajax.readyState == 4) {
            if (ajax.status == 200) {
                console.log('achou o endereço ' + info[i]);
            } else {
                console.log('nao achou o endereço ' + info[i]);
            }
        }
    }
    
    ajax.open('GET', proxy + url + info[i], true);
    ajax.send();
}

  • Thank you very much! I help very much! =)

Browser other questions tagged

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