如何等待AJAX​​响应

时间:2010-11-06 22:22:19

标签: ajax

我想知道如何在系统中暂停以等待AJAX​​请求中服务器的答案?

var method = childs[cont].getAttribute('method');
            var address = childs[cont].getAttribute('address');
            /*
             * Making the AJAX connection 
             * and returning the results.
             */
            phone = new ConstructorXMLHttpRequest();
            onreadystatechange = function(){
                switch(phone.readyState){
                    case 0: if(phone.readyState == 0){
                        break;
                    }
                    case 1: if(phone.readyState == 1){
                        break;
                    }
                    case 2: if(phone.readyState == 2){
                        break;
                    }
                    case 3: if(phone.readyState == 3){
                        break;
                    }
                    case 4: if(phone.readyState == 4){
                        if(phone.status == 200){
                            var val = phone.responseText; 
                            alert([val,1]);
                            dataInsert(val);
                            break;
                        }
                        else{
                            alert("Problemas status:"+phone.status+" state:"+phone.readyState);
                            break;
                        }
                    }
                }
            };
            phone.onreadystatechange = onreadystatechange;
            if (method == 'POST'){
                phone.open(method, address, true);
                phone.setRequestHeader("Content-type", "multipart/form-data");
                phone.send(xml2string(prepCall(childs[cont])));
            }else if(method == 'GET'){
                phone.open(method, address, true);
                phone.setRequestHeader("Content-type", "multipart/form-data");
            }

1 个答案:

答案 0 :(得分:3)

您的代码看起来不错。记住AJAX是异步的,所以不要实际暂停,只需将回调挂钩到ajax请求,该请求将在请求完成后执行。

在您的情况下,如果请求成功完成,它将发出警报并执行dateInsert函数。