Lotus@ 2016-01-25 13:39 采纳率: 100%
浏览 21

递归jQuery Ajax

I want my function to process the results, then call itself from the done callback.

function geocode(id) {
    console.log(id + ' geocode');
    $.ajax({
        url: '/customers/' + id + '/geocode',
        dataType: 'json',
        data: {
            id: id,
        }
    }).done(function() {
        var newID = id++;
        console.log(id + ' done.');
        geocode(newID);
    });
}

This isn't incrementing though, say if I start it at 1, it just loops on 2 forever. I know it's a pain returning data from ajax, but I've never fully got my head round the nuances

  • 写回答

2条回答 默认 最新

  • weixin_33713503 2016-01-25 13:42
    关注

    You need to increment the variable before you set it to the value of newId:

    function geocode(id) {
        console.log(id + ' geocode');
        $.ajax({
            url: '/customers/' + id + '/geocode',
            dataType: 'json',
            data: {
                id: id,
            }
        }).done(function() {
            console.log(id + ' done.'); // show this before incrementing
            var newID = ++id; // note the operator order here
            geocode(newID);
        });
    }
    

    Working example

    评论

报告相同问题?