1

我正在执行几个 .getJSON 调用,如果其中任何一个调用成功,我会尝试将 bool 设置为 true,这样我就可以在页面的其他位置执行其他操作。我试图使用 jquery 的 .data() 函数,但我似乎无法从 .getJSON 回调中设置它。例如:

$('#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'));

打印错误,即使我知道数据通过了。我认为这会起作用,因为 .data() 使用缓存来存储键/值对。我如何标记成功?感谢任何帮助!

4

2 回答 2

3

您必须牢记代码实际运行的顺序。您的代码实际上将按以下顺序运行:

$('#citations_button').data('citations', false);
$.getJSON(apaurl, ..., "html");
console.log("citations? "+$('#citations_button').data('citations'));

然后,最终,当异步请求返回时,它将运行您的回调函数:

$('#apacite').html("<td class=\"bibInfoLabel\">APA Citation</td><td class=\"bibInfoData\">"+data+"</td>");
$('#citations_button').data('citations', true);

当然,您最终会设置citations为 be true,但要等到您已经将其false值打印到控制台很久之后。

如果您只想在获得 JSON 数据后做某事,那么该代码绝对必须在该回调函数中(或者必须从该回调函数中调用,当然)。

如果您需要等待所有调用的结果,您可以执行以下操作:

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");
于 2010-06-09T00:27:48.187 回答
0

将您所描述的“在页面上的其他地方做一些其他事情”放在一个函数中。在 $.getJSON() 回调中调用该函数

于 2010-06-09T00:43:23.367 回答