简体   繁体   English

使用一个 function 处理多个 Ajax 请求 - 在页面加载时返回相同的结果

[英]Using one function to handle multiple Ajax requests - returning same results on page load

I'm writing some code where there will be one function (doAjax) to handle all the requests for different functionalities.我正在编写一些代码,其中将有一个 function (doAjax) 来处理对不同功能的所有请求。 This is working fine when used in the normal sense (clicking buttons, etc), but I'm trying to call a few things when the page is loaded to initialise the state of the application.这在正常意义上使用(单击按钮等)时工作正常,但我试图在加载页面时调用一些东西来初始化应用程序的 state。

Here's the Ajax function:这是 Ajax function:

function doAjax(type, action, data = null){
    return new Promise(function(res,rej){
        xhr = new XMLHttpRequest();
        xhr.open(type, '/inc/functions.php?action='+action, true);
        xhr.timeout = 20000;
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onload = function() {
            if (this.status === 200) {
                res(xhr);
            } else {
                console.log("some xhr error occured");
                rej("some xhr error happened");
            }
        };
        xhr.send(data); 
    });
}

And here are a couple of examples of functions that send requests to this:这里有几个向它发送请求的函数示例:

/* get file structure of files */
function buildTree(){
     doAjax('GET', 'get_files').then(r => {
         var res = JSON.parse(r.response);
         console.log(res);
         /*
              the json is processed here and stuff 
              is displayed on the front end
         */

     }
}

/* get user data from database */
function populateShare(){
    doAjax('GET', 'social_populate').then(r => {
        var res = JSON.parse(r.response);
        console.log(res);
        /*
            again, the json received from the database is 
            processed and output to the front end
        */
    }
}

I should also mention these functions are also bound to click listeners, so are used in the application later as well as onload!还要提一下,这些函数也绑定了点击监听,所以后面的应用和onload都会用到!

Now, the problem is when I try and execute both of these on page load as a kind of initialise function (to set up the application ready for use).现在,问题是当我尝试在页面加载时执行这两个作为一种初始化 function (设置应用程序准备使用)。 If I run the below:如果我运行以下命令:

 function init(){
     buildTree();
     populateShare();
 }
 init(); //called later

Both console.logs output the same result - the return from social_populate (called from populateShare()).两个 console.logs output 的结果相同 - 从 social_populate 返回(从 populateShare() 调用)。

So my question ultimately is whether there are any ways to queue function calls in the init() function, waiting for each to finish before moving onto the next?所以我的问题最终是是否有任何方法可以在 init() function 中对 function 调用进行排队,等待每个完成后再进入下一个? There may be more functions that need to be called on init(), some also involving Ajax requests.在 init() 上可能需要调用更多的函数,有些还涉及 Ajax 请求。

I have tried the following, found in another thread - but unfortunately returns the same result:我尝试了以下方法,在另一个线程中找到了 - 但不幸的是返回了相同的结果:

async function initialise(){
     try {
         const p1 = buildTree();
         const p2 = populateShare();
         await Promise.all([p1, p2]);
     } catch (e) {
         console.log(e);
     }
}

I know I could load the entire lot from the back end and return in one huge JSON, but I'm more curious to whether the above can be achieved, I feel like I've entered some kind of synchronous request death loop, or I'm missing something blatantly obvious here!我知道我可以从后端加载整个批次并返回一个巨大的 JSON,但我更好奇以上是否可以实现,我觉得我进入了某种同步请求死循环,或者我我在这里遗漏了一些明显的东西!

Also, no jQuery please!另外,请不要 jQuery!

Thanks!谢谢!

You appeared to have accidentally used global variable when you declare xhr which was overwritten at each call.当您声明在每次调用时被覆盖的xhr时,您似乎意外使用了全局变量。

Try let xhr = new XMLHttpRequest();试试let xhr = new XMLHttpRequest();

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

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