开发者

Looping jquery ajax based on ajax response.. with setTimeout

So I'm trying to use a single jquery function that uses ajax to talk to a single php page but calls different steps of a process. If the process step completes successfully, it returns the next step so that i can loop through the function again... until I return a 'complete' or 'fail'. I want to time certain steps of the process to account for delayed serverside processing. I'm having trouble using setTimeout inside of the function. I have the following:

    function ProcessClient(InProcess){
    var dataString = 'inprocess='+InProcess;
    if(InProcess=='buildaccount'){dataString+='&vercode='+$('#vercode').val();}

    //append current step(status) to client here

    $.ajax({             
        type: "POST",             
        url: 'ajax/NewClient.php',            
        data: dataString, 
    开发者_如何学编程    success: function(data){
            if(data=='Fail'){
                alert(data);
            }else if(data=='Complete'){
                $('#Progress').append('<li>All done! Click <a href="/manage/">here</a> to head over to your administration page!</li>');
            }else{
                var Timer = 1000;
                if(data=='buildserveraccounts'){
                    Timer=10000;
                }

                $(function(){
                    setTimeout('ProcessClient('+data+')',Timer);
                })
            }
        }
    });     
}

What am I doing wrong here? As of now... the function isn't even looping.. I've tried a few different things and can never get the timer to work. Oh and I'm open to ideas on better ways to accomplish what I'm trying to... ?


This code is suspect in a couple of ways:

$(function(){
    setTimeout('ProcessClient('+data+')',Timer);
})

The first thing is you're passing a function into $(), which is shorthand for $(docmument).ready(...) — e.g., the "call me when the DOM is ready" hook. This code has nothing to do with DOM ready. That would be relatively harmless here because if the DOM is already ready, jQuery calls the function immediately, but it's unnecessary at best.

The second thing is that you're passing a string into setTimeout. There's almost never a good reason to do that, it's the same as using eval (but with the delay), which there's also almost never a reason to use. Instead, pass in a function reference.

So:

setTimeout(function() {
    ProcessClient(data);
}, Timer);

I expect the reason it wasn't working at all was that the string you were passing into setTimeout was ProcessClient(SomeDataTest) rather than ProcessClient("SomeDataTest") (note the quotes), and so when the string was evaluated later, it was a syntax error and not executed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜