开发者

How do I protect against getJSON not calling the callback?

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 the开发者_Go百科re 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?


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:

$.ajax({
  url: "test.html",
  dataType: "json",
  success: function(html){
     $form.submit();
  },
  error: function(xhr, error){
     console.debug(xhr); 
     console.debug(error);
     $form.find(":input").attr("disabled", false);
  }
});


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


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 :

$.getJSON("a.json", function() {}).error(function() {}) 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜