Return $.get data in a function using jQuery

前端 未结 6 1339
臣服心动
臣服心动 2020-11-29 20:29

I\'m trying to call a function that contains jQuery code. I want this function to return the results of the jQuery statement. It is not working, and I\'m trying to figure ou

6条回答
  •  日久生厌
    2020-11-29 20:52

    An efficient way is to use jQuery's Deferred method, both sync/async requests to server and wait for deferred.resolve() and then return the deferred promise object. Looks a bit tedious, but a little study is sure helpful for large data. ( tvanfosson's function works well in this case, but when I was working on google analytics data, a large amount of information made me crazy and thus i need to find this solution)

         function showResults(name) { 
            var deferred = $.Deferred, requests = [];
    
            requests.push($.ajax({url:"/path/to/uri/?name=" + name, type: "GET", async: false}).done(function(d) { 
             //alert or process the results as you wish 
            }));
            $.when.apply(undefined, requests).then(function() { deferred.resolve(); }); 
            return deferred.promise();
    
        }
    

    the returned promise object can also be used with $.when(showResults('benjamin')).done(function() { }); for post modifications (like chart/graph settings etc). totally reusable. You may also put this function in a loop of $.deferred requests like,

            function updateResults() { 
                 var deferred = $.Deferred, requests = [];
                 requests.push($.ajax(url:"/path/to/names/?nameArr=" + jsonArrOfNames, type: "GET", async: false}).done(function(res) {  requests.push(showResults(res[0]));}) );
                 $.when.apply($, requests).then(function() { deferred.resolve(); }); 
                 return deferred.promise();
                }
    

提交回复
热议问题