简体   繁体   中英

Loop back through AJAX function - Causing infinite loop

I am so so stuck with this. I have a functionA which I want to call functionB (my API call) and have it return the results of the data. The API is a "queue" and "get" type. It should run like this:

  1. Run API query with "queue" type
  2. Collect returned reportID
  3. Run API query with "get" type and reportID
  4. Collect data into myfunction

This is my current code:

function myfunction() {
  var ref;
  var type = "queue";
  var metric = "pageviews";
  var post = getReport(ref, type, metric);
    post.done(function (r) {
        console.log (r);
        }
    );
}

function getReport(ref, type, metric) {
   return $.ajax({
        url: "report.php", 
        dataType: 'json',
        data: { 
            ref: ref,
            type: type, 
            metric: metric
        }
    });
}

This works fine. However I can't get the loop working correctly for the second part of my query. This is what I tried:

function myfunction() {
  var ref;
  var type = "queue";
  var metric = "pageviews";
  var post = getReport(ref, type, metric);
    post.done(function (r) {
        if (type == "queue")
        {
        myfunction(r.reportID,"get");
        }
        else if (type == "get")
        {
        console.log(r);
        }
    );
}

I keep overwriting the value of type which seems to cause an infinite loop.

Here's a basic solution that chains (actually: nests) the API calls:

function myfunction(ref) {
  getReport(ref, "queue", "pageviews").done(function(r1) {
    getReport(r1.reportID, "get", null).done(function(r2) {
      console.log(r2);
    })
  });
}

function getReport(ref, type, metric) {
  return $.getJSON("report.php", {
    ref: ref,
    type: type,
    metric: metric
  });
}

(I'm guessing how your API works / what it returns but it should be easy enough to fit)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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