简体   繁体   中英

jQuery.getJSON with JSONP is returning the same data for different calls

I'm using jQuery.getJSON() to hit the same web service three times in a row with different parameters. Then I'm drawing charts with the data I receive. The problem though is quite basic, it doesn't have to do with the chart at all. When I get the data in my callback function it is not consistently the "right" data. For example:

var URL1 = http://mysite.com/myAPI/metrics?type=pageloads&date=02022012&callback=?
var URL2 = http://mysite.com/myAPI/metrics?type=formsubmissions&date=02232012&callback=?
var URL3 = http://mysite.com/myAPI/metrics?type=uniqueusers&date=02022012&callback=?

var getDataAndDraw = function(metricURL, chartDiv) {
    $.getJSON(metricURL, function(data){
        console.log(data.metricName);

        // i do my charting here
    });
};

getDataAndDraw(URL1, 'pageloadsDiv');
getDataAndDraw(URL2, 'formsubmissionsDiv');
getDataAndDraw(URL3, 'uniqueuserDiv');

Sometimes I get the right 3 graphs and the console displays the expected metric names. But sometimes I get some mix of the same ones. For example... I'll be displaying the pageloads metrics twice and uniqueuser metrics once and console will show that the data for pageloads was returned twice and uniqueuser once.

Any ideas why this would be happening?

The AJAX requests are likely being cached. This code should fix that problem.

$(document).ready(function() {
  $.ajaxSetup({ cache: false });
});

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