weixin_33737774 2016-07-19 18:09 采纳率: 0%
浏览 37

循环和ajax的困难

I'm trying to do a check via ajax various elements of an array. However, I am unable to run the loop correctly. can you help me?

https://jsfiddle.net/mzpsLvo6/

var codReferencia = ['1111','2222','3333','4444'];

$.each(codReferencia, function(index, val) {
    $.ajax({
        url: "https://webapi.toqueacampainha.com.br/api/estoque/produtoprontaentrega?refid=" + codReferencia,
        dataType: 'json'
    })
    .done(function(data) {
        if ( data >= '1' ) {
            console.log('do anything');
        } else {
            console.log('do not do anything');
        };
    });
});
  • 写回答

1条回答 默认 最新

  • weixin_33674976 2016-07-19 18:18
    关注

    You are passing the entire array each time. You need to use your index argument and only pass the current element you are looping over.

    var codReferencia = ['1111','2222','3333','4444'];
    
    $.each(codReferencia, function(index, val) {
        $.ajax({
            url: "https://webapi.toqueacampainha.com.br/api/estoque/produtoprontaentrega?refid=" + codReferencia[index],
            codeReference: codReferencia[index],
            dataType: 'json'
        })
        .done(function(response) {
            if ( response >= '1' ) {
                console.log('do anything: ' + this.codeReference);
            } else {
                console.log('do not do anything');
            };
        });
    });
    
    评论

报告相同问题?