我正在使用 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);
});
我的问题
- 当对服务器的某个调用导致异常(失败场景)或任何其他场景的错误处理时,我该如何进行错误处理?
- 既然我在这里发出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/