为 ajax (jQuery) 设置超时 [英] Set timeout for ajax (jQuery)

查看:34
本文介绍了为 ajax (jQuery) 设置超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$.ajax({
    url: "test.html",
    error: function(){
        //do something
    },
    success: function(){
        //do something
    }
});

有时 success 功能运行良好,有时则不然.

Sometimes success function works good, sometimes not.

如何设置这个ajax请求的超时时间?例如,3 秒,如果超时,则显示错误.

How do I set timeout for this ajax request? In example, 3 seconds, if time is out, then show an error.

问题是,ajax 请求会冻结块直到完成.如果服务器宕机一段时间,它永远不会结束.

The problem is, ajax request freezes the block until finishes. If server is down for a little time, it will never end.

推荐答案

请阅读 $.ajax 文档,这是一个涵盖的主题.

Please read the $.ajax documentation, this is a covered topic.

$.ajax({
    url: "test.html",
    error: function(){
        // will fire when timeout is reached
    },
    success: function(){
        //do something
    },
    timeout: 3000 // sets timeout to 3 seconds
});

您可以通过访问 error: function(jqXHR, textStatus, errorThrown) 选项的 textStatus 参数来查看抛出的错误类型.选项是超时"、错误"、中止"和解析器错误".

You can get see what type of error was thrown by accessing the textStatus parameter of the error: function(jqXHR, textStatus, errorThrown) option. The options are "timeout", "error", "abort", and "parsererror".

这篇关于为 ajax (jQuery) 设置超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆