简体   繁体   English

jQuery-对一个AJAX调用的多功能调用

[英]Jquery - Multiple function calls to one AJAX call

I have a page that should load after the initial page load a bit of data trough AJAX that is then used in a few functions. 我有一个页面,该页面应在初始页面加载一些通过AJAX的数据之后加载,然后将其用于一些功能。

So far I can only get it to work with loading the AJAX requests separately (which means the same request is called like 30 times) 到目前为止,我只能使它与单独加载AJAX请求一起工作(这意味着同一请求被调用了30次)

What I need is the possibility to have a function that can be called multiple times, but only activates the AJAX call once and the other times gives the data back without having again the same AJAX call that already gave the data back running (cause that's redundant and not needed, the data doesn't change). 我需要的是可能具有可以多次调用的功能,但是只能激活一次AJAX调用,而其他时候却可以返回数据,而不必再次执行已经使数据重新运行的同一AJAX调用(这是多余的)并且不需要,数据不会更改)。

Now I could do that by simply making a call and store it in a global variable and just check if something is in this variable or not... 现在,我可以通过简单地进行调用并将其存储在全局变量中,然后仅检查此变量中是否有内容来做到这一点...

BUT! 但! The "but" is the problem, that these around 20 calls that need the information the AJAX delivers happen right after the DOM is loaded, right together with the AJAX call. 问题是,但是,大约20个需要AJAX传递信息的调用在加载DOM之后立即发生,并且与AJAX调用一起发生。

And so I cannot do that, because the 20 requests happen before the first AJAX call even finished showing all data. 因此,我无法执行此操作,因为20个请求是在第一个AJAX调用甚至还没有显示完所有数据之前发生的。

I tried to do some stuff with JQueries "deferred", but could only manage to do it with one call and not with multiple calls at almost the same time without that it triggers the AJAX call everytime. 我试图用“延迟”的JQueries做一些事情,但是只能设法通过一个调用而不是同时进行多个调用来做到这一点,而这不会每次都触发AJAX调用。

But I'm sure that must be possible somehow! 但是我敢肯定这一定有可能! Nicely, without some sort of loops and timeout. 很好,没有任何循环和超时。 I really like the idea of loading pages and parts of pages partially. 我真的很喜欢部分加载页面和部分页面的想法。 Input field isn't loaded right from the start, but gets delivered as soon as it is ready, etc... 输入字段不是从一开始就加载的,而是在准备就绪后立即交付,等等。

Is it? 是吗? I really can't wrap my head around this one... 我真的无法绕过这个...

$(function(){
    loadme1();
    loadme2(); /* loaded from complete different parts in the code, so not possible to start loadme2 only after loadme1 has everything finished */
});

function getData(){ 
    return $.get("/pathtogetthedata", {}, function(data){

    });
}

function loadme1(){
    getData().done(function(data){           
        var obj = $.parseJSON(data); 
        /* do something with obj */
    }
}
function loadme2(){
    getData().done(function(data){ //please just wait till the first call to the same method finished and give me that data or wait till it's in a global variable and I take it from there. Only make a call if there is no jquery "promise" waiting    
        var obj = $.parseJSON(data); 
        /* do something with obj */
    }
}

You have to keep all the "callback" and then when the data ready, to call the callback you just saved for example: 您必须保留所有“回调”,然后在数据准备就绪时,调用刚刚保存的回调,例如:

var funcs = []

function exampleOfAjaxGetData(callback) {
    funcs.push(callback)
    if (funcs.length == 1) {
        setTimeout(function() {
            alert('This is need to be called once1')
            while (funcs.length > 0)
                funcs.pop()('The data return from ajax')
        }, 2000)
    }
}


exampleOfAjaxGetData(function(x) {
    alert('I got the data:' + x)
})

exampleOfAjaxGetData(function(x) {
    alert('I got the data:' + x)
})

jsFiddle: http://jsfiddle.net/yn5ayw30/ jsFiddle: http : //jsfiddle.net/yn5ayw30/

In the example I show you a function that takes 2 seconds to complete. 在示例中,我向您展示了一个需要2秒才能完成的功能。 I called the function twice. 我两次调用了该函数。 But the "setTimeout" run only once. 但是“ setTimeout”仅运行一次。 When setTimeout complete, it will run all the function that wait for answer. setTimeout完成后,它将运行所有等待答案的功能。

I can think of one solution here it is : 我可以想到一个解决方案是:

var adata = -1; // global variable data holder

function getdata()
{
    //if ajaxx call is already done and completed then return data
    if(adata != -1 && adata != -2)return adata;

    if(adata == -1) 
    {
        //function getting called first time

        adata = -2; // now we change value of adata to -2
        // we will use this -2 to check if ajaxx call is stil running
        //do ajaxx $.get call
        $.get( "url_goes_here", function( data ) {
            adata = data;// assingh received data to adata, so -2 is changed now
        });
        //now code will move to while loop part even after first call as while loop part doesn't have condition
        //thus waiting for ajaxx call to be completed even if its first call
    }
    while(adata == -2){ 
        //just a loop to delay output until call finishes
    }
    return adata;

}

Now you can use getdata() function to achieve what you want 现在您可以使用getdata()函数来实现所需的功能

var getDataCalled = false;
var deferred = $.Deferred();
function getData(){ 
    if(!getDataCalled) {
        getDataCalled = true;
        return $.get("/", {} , function(data) {
              deferred.resolve(data);
        });
    } else {
         console.log("returning deferred");
         return deferred;  
    }
}

How about you save when you first call your "getData" function. 第一次调用“ getData”函数时如何保存。 When it has already been called you return your own "deferred" object back and resolve it when your first ajax request is finished. 当它已经被调用时,您可以返回自己的“ deferred”对象,并在您的第一个ajax请求完成时对其进行解析。 I hope this short code snippet speaks for itself and is easy to understand. 我希望这个简短的代码片段能说明一切,并且易于理解。

Calling getData() will now first make the ajax request and after that always return a deferred object you created yourself. 现在,调用getData()首先会发出ajax请求,然后始终返回您自己创建的延迟对象。

getData().done(function(data) {
  console.log(data);
});
getData().done(function(data) {
  console.log(data);
});
getData().done(function(data) {
  console.log(data);
});

You will see there will only be one ajax request. 您将看到只有一个ajax请求。

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

相关问题 延迟了jquery的多个ajax调用-如果一个调用失败,是否有一种方法可以不拒绝 - multiple ajax calls with jquery deferred - is there a way to not reject if one call fail 然后延迟Jquery调用多个ajax调用(3次并行调用,然后再完成一个ajax调用) - call multiple ajax call with Jquery deferred When and then(3 parallel calls and then on complete one more ajax call) 如何并行调用多个独立的jquery ajax调用以及完成后如何调用函数 - How to call multiple independent jquery ajax calls in parallel and call function when they all finish 在一个JavaScript函数中使用多个Ajax调用 - Using multiple ajax calls in one javascript function 设计:一个AJAX调用或多个AJAX调用以获取详细信息列表 - Design : One AJAX Call or multiple AJAX calls to get list of details jquery中的多个ajax调用 - Multiple ajax calls in jquery jQuery Ajax多个调用 - Jquery ajax multiple calls jQuery:$ .when延迟的AJAX呼叫-一个失败的呼叫会取消其他呼叫 - jQuery: $.when deferred AJAX calls — one failed call cancels others AJAX来自同一功能的多次调用,某些回调无法正常工作 - AJAX multiple calls from the same function, some call backs not working 使用多个jquery .ajax()调用将一个下拉列表的值传递给另一个下拉列表 - Pass value of one dropdown to another using Multiple jquery .ajax() calls
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM