即使在页面重定向之后,ajax调用也会结束吗?



我正试图为本地图像创建一个临时图像url,并将其发送到谷歌通过图像进行搜索。我不希望图像url是永久的,所以我想删除它后,我使用它。我有下面的代码:

// Gets a URL that can be used to do a search by image through Google.
function getImageURL() {
    var xml = new XMLHttpRequest();
    xml.onreadystatechange = function () {
        if (xml.readyState == 4 && xml.status == 200) {
            deleteImageURL(); // asynchronous call to server to delete the URL
            window.location.href = 
                "https://www.google.com/searchbyimage?site=search&sa=X&image_url=" 
                + xml.responseText; // the image url
        }
    }
    xml.open("GET", "REST_ENDPOINT", true);
    xml.send();
}

上面的函数调用服务器,当它完成时,将删除url并重定向页面。函数"deleteImageURL()"是另一个异步完成的ajax调用。目前,这加载谷歌页面很好,因为图像URL没有完成删除URL的时间重定向发生。

我的问题是:deleteImageURL()将完成删除图像URL,即使在页面重定向后,还是会停止(因此,永远不会删除URL)?

编辑:所以我在想你们说什么关于竞争条件,并尝试以下代码代替:

// Gets a URL that can be used to do a search by image through Google.
function getImageURL() {
    var xml = new XMLHttpRequest();
    xml.onreadystatechange = function () {
        if (xml.readyState == 4 && xml.status == 200) {
            deleteImageURL(xml.responseText);
        }
    }
    xml.open("GET", "REST_ENDPOINT"
        + id + "/public_url", true);
    xml.send();
}
// Deletes the url for the image.
function deleteImageURL(imageURL) {
    var xml = new XMLHttpRequest();
    xml.open("GET", "REST_ENDPOINT_FOR_DELETE", true);
    xml.send();
    window.location.href = 
            "https://www.google.com/searchbyimage?site=search&sa=X&image_url="
            + imageURL;
}

这段代码每次运行都能正常工作。我认为可能仍然存在竞争条件,但到目前为止似乎工作得很好。

再次感谢。

"deleteImageURL()"将在页面重定向后完成删除图像URL。参考:我应该等待ajax完成重定向页面吗?

服务器不会停止处理请求(由deleteImageUrl发起),但是如果当前页面在操作完成之前在浏览器中卸载,您将无法处理回调。

如果deleteImageURL();包含异步调用,您应该在调用完成时进行重定向。当调用是同步时,您的代码将正常工作。我们没有看到deleteImageURL();的来源,可以更具体,但你应该做同样的事情,你已经做了getImageURL()

最新更新