如何只显示最后一个ajax请求结果

时间:2017-02-10 03:18:46

标签: javascript jquery ajax

总计ajax请求的数量,并在最后一次ajax响应时显示ajax响应。

换句话说,如何仅使用上次发送的ajax请求的响应。

var req=0;
function ajaxReq(){
    req++; /total up the amount of request/
    $.ajax({
        url: "result.php",
        type: 'GET',
        contentType: false,
        enctype: 'multipart/form-data',
        cache: false,
        processData: false,
        success: function(response) {
            if(req==1){ /show the response when this is the last request/
                $("#response-element").html(response);
            }
            req--; /Subtract when every success ajax response/
        }
    });
}

我在查看邮件详细信息时使用此功能 如果用户在响应显示之前单击了几个线程,它将显示当前所选线程详细信息显示之前的前一个线程详细信息

任何更好的解决方案都适合分享

2 个答案:

答案 0 :(得分:1)

您发送请求后应立即减少。

var req=""; // should be a number
function ajaxReq(){
    req++; /total up the amount of request/
    $.ajax({
        url: "result.php",
        type: 'GET',
        contentType: false,
        enctype: 'multipart/form-data',
        cache: false,
        processData: false,
        beforeSend: function() {
            if (req > 1) req -= 1;
        },
        success: function(response) {
            if(req==1){ /show the response when this is the last request/
                $("#response-element").html(response);
                req -= 1;
            }
        }
    });
}

答案 1 :(得分:1)

你或多或少都在正确的路线上。这是避免以前调用回调的唯一方法。您必须将ID与每个请求相关联,然后检查请求的ID是否是最后发送的请求。

.jsx,
相关问题