我正在做几个.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()使用缓存来存储键/值对。如何标记成功??感谢您的帮助!!
发布于 2010-06-09 08:27:48
您必须牢记代码实际运行的顺序。您的代码实际上将按以下顺序运行:
$('#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设置为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-09 08:43:23
将你所描述的“在页面的其他地方做一些其他事情”放在一个函数中。在$.getJSON()回调中调用该函数
https://stackoverflow.com/questions/3002294
复制相似问题