Ajax形式超时

时间:2016-09-27 09:15:54

标签: javascript php jquery ajax

我有一个 PHP页面,表单,其中包含100个字段。我在输入数据时使用 Ajax获取内容到每个字段。

有时,我发生了这个错误:

  

净:: ERR_CONNECTION_TIMED_OUT

大概是因为服务器无法按时响应。当发生这种情况时,会出现错误,Ajax将无法继续工作。

有没有一种方法可以让代码在错误发生后执行?这样我可以继续尝试Ajax吗?

注意:我使用普通的 XMLHttpRequest()请求,而不是jquery函数

2 个答案:

答案 0 :(得分:1)

在你的ajax代码中尝试将超时设置定义为0(无限制):

$.ajax({
timeout: 0, //Set your timeout value in milliseconds or 0 for unlimited

您可以将此值设置为3秒(3000)并使用错误功能捕获异常。像这样:

error: function(jqXHR, textError, errorThrown) {
    if(textError==="timeout") {  
        alert("Call has timed out"); //Handle the timeout
    } else {
        alert("Unknown error"); //Handle other error type
    }

希望有所帮助

答案 1 :(得分:-1)

您可以使用此功能捕获您在ajax中可以获得的所有错误:

$.ajax({
    url: "your_url",
    type: "GET",
    dataType: "json",
    timeout: 5000, /* timeout in milliseconds */
    success: function(response) { alert(response); },
    error: function(jqXHR, exception) {
        if (jqXHR.status === 0) {
            return ('Not connected.\nPlease verify your network connection.');
        } else if (jqXHR.status == 404) {
            return ('The requested page not found. [404]');
        } else if (jqXHR.status == 500) {
            return ('Internal Server Error [500].');
        } else if (exception === 'parsererror') {
            return ('Requested JSON parse failed.');
        } else if (exception === 'timeout') {
            return ('Time out error.');
        } else if (exception === 'abort') {
            return ('Ajax request aborted.');
        } else {
            return ('Uncaught Error.\n' + jqXHR.responseText);
        }
    }
});​
相关问题