简体   繁体   English

如何使用应用于XMLHttpRequest的ajaxComplete

[英]How can I use ajaxComplete applied to a XMLHttpRequest

I'm doing an asynchronous request to load a json file using XMLHttpRequest(). 我正在执行异步请求,以使用XMLHttpRequest()加载json文件。 I would need to wait for the request completion before going on with the rest. 我需要先等待请求完成,然后再进行其余操作。

I saw the ajaxComplete() should do just this, but I can't apply it to my actual code and get it working. 我看到ajaxComplete()应该做到这一点,但是我无法将其应用于我的实际代码并使之正常工作。

Here I'm setting up the function that calls the json via asynchronous request 在这里,我设置了通过异步请求调用json的函数

function ajaxCall(){

    xmlhttp.onreadystatechange = function(){

        if(xmlhttp.readyState==4 && xmlhttp.status==200){
            arrayImages = JSON.parse(xmlhttp.responseText);
            output(arrayImages);
        }
    }

    xmlhttp.open("GET", url, true);
    xmlhttp.send();

}

Here I'm calling that function 在这里我叫那个功能

ajaxCall();

Now I want that it is completed 现在我希望它完成

do other things

Any help ? 有什么帮助吗?

Thanks! 谢谢!

You have two options. 您有两个选择。

A Promise 一个承诺

function ajaxCall(){
    return new Promise(function(success){
        xmlhttp.onreadystatechange = function(){
            if(xmlhttp.readyState==4 && xmlhttp.status==200){
                arrayImages = JSON.parse(xmlhttp.responseText);
                output(arrayImages);
                success();
            }
        }
        xmlhttp.open("GET", url, true);
        xmlhttp.send();
    });
}

Then you can do stuff when it's done 然后,您可以在完成后做一些事情

ajaxCall().then(function(){
    // Do stuff after
});

Or you can use a callback... 或者您可以使用回调...

function ajaxCall(callback){
    xmlhttp.onreadystatechange = function(){
        if(xmlhttp.readyState==4 && xmlhttp.status==200){
            arrayImages = JSON.parse(xmlhttp.responseText);
            output(arrayImages);
            callback();
        }
    }
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

Then do stuff after like this 然后像这样做东西

ajaxCall(function(){
    // do stuff after
});

ajaxComplete is part of the jQuery library. ajaxComplete是jQuery库的一部分。 It only binds itself to jQuery ajax requests. 它仅将自身绑定到jQuery ajax请求。 While these usually wrap XMLHttpRequest, they can't touch XMLHttpRequest when you use it manually. 尽管这些通常包装XMLHttpRequest,但是当您手动使用XMLHttpRequest时,它们无法触摸XMLHttpRequest。

To run some code after the response is back, you need to wait for a suitable event. 要在响应返回后运行一些代码,您需要等待适当的事件。 You are already doing that here: 您已经在这里这样做了:

 if(xmlhttp.readyState==4 && xmlhttp.status==200){ 

Place the code you want to run after the response is received inside that if statement. 在收到响应后,将要运行的代码放入该if语句中。

If you want to make ajaxCall reusable, then pass a function to it as an argument, then call that function inside the if statement. 如果要使ajaxCall可重用,则将一个函数作为参数传递给它,然后在if语句内部调用该函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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