简体   繁体   中英

jQuery ajax “too much recursion”

I have an procedure that runs throught 5 consecutive steps, and in my page, I'm calling an ajax method for each of them.

The idea is to run the first, if all is ok the second, and so on.

My code is:

$("#foo").click(function(){
    $.ajax({
        url: 'ajax.php',
        async: false,
        data: {
            step: 1
        },
        dataType: 'json',
        type: 'GET',
        success: walk_through(data)
    });
});

function walk_through(data)
{
    if(data.status == 'ok')
    {
        if(data.next_step == 'end')
        {
            // All steps completed
        }
        else
        {
            // Current step completed, run next one
            $.ajax({
                url: 'ajax.php',
                async: false,
                data: {
                    step: data.next_step
                },
                dataType: 'json',
                type: 'GET',
                success: walk_through(data)
            });
        }
    }
    else
    {
        alert("Error.");
        console.log(data);
    }
}

Im getting "too much recursion" error, even if my ajax calls are set as syncronous.. why?

Change

success: walk_through(data)

To

success: walk_through

You want the function walk_through to be the success handler, but you don't want to call the function immediately.

Your JavaScript is wrong on your AJAX call:

$.ajax({
    url: 'ajax.php',
    async: false,
    data: {
      step: data.next_step
    },
    dataType: 'json',
    type: 'GET',
    success: walk_through //You had walk_through(data), which makes a function call, rather than a reference to a function.
});

Your walk_through function is calling itself everytime it is succesful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM