I'm doing a couple of .getJSON calls and if any one of them succeeds, I'm trying to set a bool to true so I can then do some other stuff elsewhere on the page. I was trying to use jquery's .data() function, but I don't seem able to set it from inside the .getJSON callback. for example:
$('#citations_button').data('citations', false);
$.getJSON(apaurl, function(data) {
$('#apacite').html("<td class=\"bibInfoLabel\">APA Citation</td><td class=\"bibInfoData\">"+data+"</td>");
$('#citations_button').data('citations', true);
}, "html");
// other .getJSONs look like above...
console.log("citations? "+$('#citations_button').data('citations'));
prints false, even when I know the data came through. I thought this would work since .data() uses the cache to store the key/value pair. how can i flag su开发者_StackOverflowccesses?? appreciate any assistance!!
You have to keep in mind the sequence in which your code is actually run. Your code will actually run in the following order:
$('#citations_button').data('citations', false);
$.getJSON(apaurl, ..., "html");
console.log("citations? "+$('#citations_button').data('citations'));
Then, eventually, when the asynchronous request comes back, it will run your callback function:
$('#apacite').html("<td class=\"bibInfoLabel\">APA Citation</td><td class=\"bibInfoData\">"+data+"</td>");
$('#citations_button').data('citations', true);
Sure, you eventually set citations
to be true
, but not until long after you've already printed its false
value out to the console.
If you want to do something only after you've gotten your JSON data, that code absolutely must be in that callback function (or must be called from within that callback function, of course).
If you need to wait for a result from all the calls, you can do something like this:
var expectedResponses = 2;
function gotResponsesFromAllCalls() {
// Do things you can only do when ALL calls have returned.
};
$.getJSON(url1, function(data) {
// Do things specific to the return of URL 1
if (--expectedResponses == 0)
gotResponsesFromAllCalls();
}, "html");
$.getJSON(url2, function(data) {
// Do things specific to the return of URL 2
if (--expectedResponses == 0)
gotResponsesFromAllCalls();
}, "html");
Put what you describe as 'do some other stuff elsewhere on the page' in a function. Call that function in the $.getJSON() callback
精彩评论