在 .getJSON 回调中设置 jQuery .data()
我正在执行几次 .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() 使用缓存来存储键/值对。我如何标记成功?感谢任何帮助!
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 successes?? appreciate any assistance!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须记住代码实际运行的顺序。您的代码实际上将按以下顺序运行:
然后,最终,当异步请求返回时,它将运行您的回调函数:
当然,您最终将
引用
设置为true
,但要等到您将其false
值打印到控制台后才可以。如果您只想在获取 JSON 数据后执行某些操作,则该代码绝对必须位于该回调函数中(或者当然必须从该回调函数中调用)。
如果您需要等待所有调用的结果,您可以执行以下操作:
You have to keep in mind the sequence in which your code is actually run. Your code will actually run in the following order:
Then, eventually, when the asynchronous request comes back, it will run your callback function:
Sure, you eventually set
citations
to betrue
, but not until long after you've already printed itsfalse
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:
将您所描述的“在页面其他地方执行其他操作”放入函数中。在 $.getJSON() 回调中调用该函数
Put what you describe as 'do some other stuff elsewhere on the page' in a function. Call that function in the $.getJSON() callback