![](/img/trans.png)
[英]How to check if given URL exists or not in Java and JavaScript
[英]Check if a image exists with a given URL - JavaScript
我正在嘗試使用 javascript 檢查給定 url 的圖像是否存在,但我的代碼不起作用。 謝謝!
這是我的功能:
function verifyImageURL(url, callBack) {
var img = new Image();
img.src = url;
img.onload = function () {
callBack(true);
};
img.onerror = function () {
callBack(false);
};
}
我是這樣稱呼它的:
var url = "http://greenstyle.com.br/wp-content/uploads/2012/09/Tucano-imagem-Silvia-Kochen-Wordpress.jpg";
verifyImageURL(url, function (imageExists) {
if (imageExists === true) {
alert("Image Exists");
} else {
alert("Image does not Exist");
}
});
這個問題已經很久沒有活動了,但是由於我看到了另一個最近的答案,我想我會分享一個適合提問者使用回調的示例模式的解決方案,但是如果沒有提供回調參數,或者返回一個承諾:
查看TypeScript Playground 中的代碼以查看類型和重載的函數簽名
function loadImage (url, timeoutOrCallback, maybeCallback) { let timeout; let callback; if (typeof timeoutOrCallback === 'number') { timeout = timeoutOrCallback; if (typeof maybeCallback === 'function') callback = maybeCallback; } else if (typeof timeoutOrCallback === 'function') callback = timeoutOrCallback; const promise = callback ? undefined : new Promise(resolve => void (callback = resolve)); const onlyRunOnce = {once: true}; let timerId = 0; let done = false; if (typeof timeout === 'number') { timerId = setTimeout(() => { done = true; callback(false); }, timeout); } const img = new Image(); img.addEventListener('load', () => { if (done) return; clearTimeout(timerId); done = true; callback(true); }, onlyRunOnce); img.addEventListener('error', () => { if (done) return; clearTimeout(timerId); done = true; callback(false); }, onlyRunOnce); img.src = url; return promise; } // Usage examples: function asyncExample (url, logId) { const timeout = 3e3; // 3s loadImage(url, timeout).then(imageLoaded => { console.log(`${logId}: async with timeout:`, imageLoaded) }); loadImage(url).then(imageLoaded => { console.log(`${logId}: async:`, imageLoaded) }); } function callbackExample (url, logId) { const timeout = 3e3; // 3s let cb = imageLoaded => console.log(`${logId}: callback with timeout:`, imageLoaded); loadImage(url, timeout, cb); cb = imageLoaded => console.log(`${logId}: callback:`, imageLoaded); loadImage(url, cb); } let url = 'https://i.stack.imgur.com/TxzmG.jpg'; asyncExample(url, 'SO image'); callbackExample(url, 'SO image'); url = 'https://invalid.example/image.jpg'; asyncExample(url, 'invalid image'); callbackExample(url, 'invalid image');
試試這個方法
var x = new XMLHttpRequest(); x.open("get", url, true);x.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) {alert('exist');}else{alert('does not exist'};}; x.send();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.