Javascript 檔案是否存在該資料夾

WICOgohome
Sep 4, 2018 · 2 min read
顯示不出的照片

這幾天看著一欄欄應該顯示照片的地方都是無法顯示,覺得應該加個提示,因為專案的seeder不包含圖檔,匯入的資料雖然有照片檔名但沒有實質檔案,造成顯示錯誤。

原先在後台用php檢查是單純的 file_exists(path),以為js也可以很簡單就解決,卻發覺js要檢查比想像中困難。

image onerror

HTML的img有個onerror,可以在錯誤發生時呼叫function或是放上預設照片。

<img src=”image.jpg” onerror=”this.src=’error.jpg’” />

我期望的功能是:照片會從pictures/preview/img.jpg載入,若載入失敗,會再從pictures/img.jpg中尋找是否有原圖,若也沒有,才跳出文字警示。

<img src=”pictures/preview/image.jpg” onerror=”this.src=’pictures/img.jpg’” />

因為兩個資料夾都找不到,圖片開始抽搐(不斷載入)。

轉往寫個funciton

<img src=”pictures/preview/”+data onerror=”Error(data)” />function Error(data).....

data is not defined.

那再換其他方式

XMLHttpRequest

它可以發出 HTTP請求,透過檢查status來決定下一步。

var req = new XMLHttpRequest();
req.open('GET', url, false);
req.send();
if(req.status === 200).....

如果找不到就會是404,儘管目的是達到了,但缺點是同一頁載入許多需要判定的圖片就會載入很慢。所以在前頭先加個

if (data === null || data==='0') return "尚未上傳照片";

讓不必要的送出不會產生,雖然這類狀況在正式機上會是少數,但還在想如何能更輕鬆解決問題。

WICOgohome

Written by

Studying

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade