如何防止 getJSON 不调用回调?
在提交表单按钮之前,我进行 $.getJSON 调用来验证一些数据,当它返回时,它要么显示“您没有正确填写此表单”对话框,要么执行 form.submit( )。但有时,特别是在我的慢速测试服务器上,调用回调之前需要几秒钟的时间,因此我想提供一些视觉指示(禁用按钮、等待光标等)来表明您已按下按钮,并且然后关闭回调中的视觉指示。但我被告知,回调可能不会被调用的可能性虽小但非零。
确保在这种情况下,我不会得到非功能形式的最佳实践是什么?
Before submitting a form button, I make a $.getJSON call that validates some of the data, and when it comes back, it either displays a "you didn't fill out this form correctly" dialog or it does the form.submit(). But sometimes, especially on my slow test server, it takes a few seconds before the callback is called, and so I'd like to put up some visual indication (disabled buttons, wait cursors, etc) that you have pressed the button, and then turning off that visual indication in the callback. But I'm told that there is a small but non-zero chance that the callback might not be called.
What is the best practice to make sure that in that situation, I don't end up with a non-functional form?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将
$.ajax
与.error 一起使用除了
回调代替.success
回调之外,还使用 $.getJSON
。如果请求失败,.error
回调将触发。您可以使用它来重新启用并显示合适的消息,类似于投票失败时 StackOverflow 上显示的消息。例子:You can use
$.ajax
with an.error
callback in addition to the.success
callback instead of$.getJSON
. If the request fails, the.error
callback will fire. You can use that to re-enable and display a suitable message, similar to the one shown on StackOverflow when a vote fails. Example:我只想使用超时。确保如果表单已启用,enableForm() 仅返回,并在禁用表单时清除超时,以避免运行多个计时器。
setTimeout(enableForm, 10000); // 在任何情况下 10 秒后启用表单
I'd simply use a timeout. Make sure that enableForm() just returns if the form is already enabled and clear the timeout when the form is disabled to avoid more than one timer running.
setTimeout(enableForm, 10000); // enables form in any case after 10s
您可以在此处查看 http://api.jquery.com/jQuery.getJSON/ jqXHR 对象部分,它解释了函数 $.getJSON() 返回一个实现 XMLHTTPRequest 的 jqXHR 对象,因此您将拥有可用的 .error、.success 和 .complete
我认为这适用于您的情况:
You can look here http://api.jquery.com/jQuery.getJSON/ in The jqXHR Object section, it explains that the function $.getJSON() returns an jqXHR Object that implements XMLHTTPRequest so you will have available .error, .success and .complete
I think this will work in your case :