如何等待ajax命令在javascript中完成

时间:2018-04-11 19:30:08

标签: javascript php ajax

我在那些突出显示的函数中有ajax java脚本不等到服务器发出请求后继续执行其他命令我不会那样

我是java脚本的新手

here code

            function putthedataback() {
                for (var i = 0; i < year.length; i++) {
                    var a = i + 1;
                    year1fun(year[i],a);
                    cc1fun(cc[i],a);
                    tp1fun(tp[i],a);
                    document.getElementById("year" + a).value = "" + year[i];
                    document.getElementById("cc" + a).value = "" + cc[i];
                    document.getElementById("tp" + a).value = "" + tp[i];
                    document.getElementById("du" + a).value = "" + du[i];
                    document.getElementById("dd" + a).value = "" + dd[i];
                    document.getElementById("ns" + a).value = "" + ns[i];
                    document.getElementById("fv" + a).value = "" + fv[i];

                }
            }

ajax one function

function year1fun(value, x) {
                        var xmlhttp = new XMLHttpRequest();
                        xmlhttp.onreadystatechange = function () {
                            if (this.readyState === 4 && this.status === 200) {
                                document.getElementById("cc" + x).innerHTML = this.responseText;
                            }
                        };
                        xmlhttp.open("GET", "yearselectionchanged.php?q=" + value, true);
                        xmlhttp.send();
                    }

here a ajax containing function

1 个答案:

答案 0 :(得分:-2)

您调用了 xmlhttp.open(“GET”,“yearselectionchanged.php?q =”+ value,true);

但最后一个参数将是假的,如下:

xmlhttp.open(“GET”,“yearselectionchanged.php?q =”+ value,false);

True 异步请求,然后您的代码不会等待响应。并且错误 同步,您的代码将等待回复。

请参阅此处的文档:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests#Synchronous_request