Ajax 调用发出的回调比预期的要多

Ajax call issues more callbacks than expected

本文关键字:回调 调用 Ajax      更新时间:2023-09-26

我有这段代码来发出 ajax 请求,但根据 Chrome 检查器的说法,与请求关联的回调被调用了两次(我的意思是响应被记录到控制台中两次),另外 2 个日志正在打印,没有任何内容。代码如下:

var ajax = {
    pull: function (settings) {
        settings.type = 'get';
        settings.callback = typeof (settings.callback) === 'function' ? settings.callback : false;
        settings.data = settings.data ? settings.data : null;
        return this.request(settings.url, settings.type, settings.callback, settings.data);
    },
    request: function (url, type, callback, data) {
        var ids = ['MSXML2.XMLHTTP.3.0',
            'MSXML2.XMLHTTP',
            'Microsoft.XMLHTTP'],
            xhr;
        if (window.XMLHttpRequest) {
            xhr = new XMLHttpRequest();
        } else {
            for (var i = 0; i < ids.length; i++) {
                try {
                    xhr = new ActiveXObject(ids[i]);
                    break;
                } catch (e) {}
            }
        }
        if (callback) {
            xhr.onreadystatechange = function () {
                callback(xhr);
            };
        }
        xhr.open(type, url, true);
        if (type.toUpperCase() === 'GET') {
            xhr.send();
        } else if (type.toUpperCase() === 'POST') {
            xhr.send(data);
        }
    }
}
ajax.pull({
    url: 'http://localhost/my/twtools/scripts/ajax.php',
    callback: function (xhr) {
        console.log(xhr.response);
    }
});

xhr.onreadystatechange 有几个步骤(从 0 前 4 个编号,我相信像 0 = 未初始化,1 = 开始等,虽然我不能再记住步骤的确切名称,快速谷歌应该找到它们),每个步骤都在调用你的回调。如果我没记错的话,最后一个阶段是 4,所以我相信你需要检查这样的东西

if (xhr.readyState == 4 && xhr.status == 200)
{
// call has finished successfully
}

在你的回调中,即检查它是否全部完成并得到成功的响应

这些天我被jQuery宠坏了(使用jQuery更容易做到),自从我写原始ajax以来已经有一段时间了。

> 您正在使用 onreadystatechange ,它被多次调用(一旦每个状态更改)。

尝试使用

xhr.onload = function() {
    callback(xhr);
};