[英]Will an ajax call finish even after a page redirect?
我正在嘗試為本地圖像創建一個臨時圖像URL,並將其發送給Google以按圖像進行搜索。 我不希望圖像網址是永久的,因此我想在使用后立即將其刪除。 我有下面的代碼:
// 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調用。 目前,這可以很好地加載google頁面,因為在重定向發生時圖像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();
包含一個異步調用,您應在調用完成后進行重定向。 調用同步時,您的代碼將起作用。 我們看不到deleteImageURL();
的來源deleteImageURL();
並且可以更具體,但是您應該執行與getImageURL()
相同的操作。
即使頁面重定向后,“ deleteImageURL()”也將完成刪除圖像URL。。參考: 我應該等待ajax完成重定向頁面嗎?
服務器不會停止處理請求(由deleteImageUrl發起),但是如果在操作完成之前在瀏覽器中卸載了當前頁面,則您將無法處理回調。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.