javascript - 使用 JQuery When 进行错误处理

标签 javascript jquery jquery-deferred

我正在使用 JQuery when 。语法如下所示:

$.when(
  // Get the HTML
  $.get("/feature/", function(html) {
    globalStore.html = html;
  }),

  // Get the CSS
  $.get("/assets/feature.css", function(css) {
    globalStore.css = css;
  }),

  // Get the JS
  $.getScript("/assets/feature.js")

).then(function() {

  // Add CSS to page
  $("<style />").html(globalStore.css).appendTo("head");

  // Add HTML to page
  $("body").append(globalStore.html);

});

我的问题

  1. 当对服务器的某个调用导致异常(失败场景)或任何其他场景的错误处理时,我该如何进行错误处理?
  2. 既然我在这里发出Ajax请求,我该如何定义Ajax请求的超时时间?

最佳答案

deferred.then( doneCallbacks, failCallbacks )可以采用失败过滤器,例如

$.when(
  // Get the HTML
  $.get("/feature/", function(html) {
    globalStore.html = html;
  }),

  // Get the CSS
  $.get("/assets/feature.css", function(css) {
    globalStore.css = css;
  }),

  // Get the JS
  $.getScript("/assets/feature.js")

).then(function() {

  // Add CSS to page
  $("<style />").html(globalStore.css).appendTo("head");

  // Add HTML to page
  $("body").append(globalStore.html);

}, function(){
    //there is an exception in the request
});

要设置超时,您可以使用timeout选项。

您可以像这样全局使用它

jQuery.ajaxSetup({
    timeout: 5000
})

或使用 $.ajax() 而不是带有 timeout 选项的简短版本 $.get()

关于javascript - 使用 JQuery When 进行错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25618593/

相关文章:

javascript - 可以取消 jQuery 延迟吗?

javascript - $.递延 : How to detect when every promise has been executed

javascript - 修复 html 元素而不考虑设备方向和运动

javascript - JQuery 根据所选选项填充表单

javascript - React Router 总是显示 IndexRoute

php - 检查 php 变量的 Jquery 覆盖

javascript - 如何在自定义格式化程序中使用外部库?

javascript - 使用 jquery 延迟对象链接多个 ajax 调用

javascript - 圆坐标到 Javascript 中的数组

javascript - 如何获取两个列表,允许用户从每个列表中进行选择以创建两个新列表并将新列表中的数据组合成 redux 中的单个结果