我正在尝试为本地图片创建临时图片网址,并将其发送给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();
}
上述功能调用服务器,完成后将删除网址并重定向页面。函数“deleteImageURL()”是另一个异步完成的ajax调用。目前,这会加载谷歌页面,因为图像网址没有在重定向发生时删除网址。
我的问题是: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;
}
每次运行时,此代码都有效。我认为仍然可能存在竞争条件,但到目前为止似乎工作正常。
再次感谢。
答案 0 :(得分:1)
如果deleteImageURL();
包含异步呼叫,则应在呼叫完成后执行重定向。当呼叫同步时,您的代码将起作用。我们没有看到deleteImageURL();
的来源并且可能更具体,但您应该像对getImageURL()
所做的那样做。
答案 1 :(得分:1)
“deleteImageURL()”即使在页面重定向后也会删除图像URL。 请参阅:Should I wait for ajax to complete to redirect a page?
答案 2 :(得分:0)
服务器不会停止处理请求(由 deleteImageUrl 启动),但如果当前页面在操作完成之前在浏览器中卸载,您将无法处理回调