2017-08-11 160 views
1

我有json飼料,給了我thumbimage網址。 這將返回URL像/webapps/CC/fileAPI/edc_eventcal/Celebrations_Todmorden%20Mills%20Harvest%20Festival_th__Vb2eHh-nEpJ8xLLEU5UFw.png顯示圖像從網站URL(json)本地顯示在本地

現在,前/ webapps /下它需要 「app.toronto.ca」 來獲得完整路徑。所以我把「localhost」換成了「app.toronto.ca」。它給了我完整的圖像路徑。

現在,麻煩的是,即使我檢索完整的URL,image.src語法仍然會強制計算機向我完美組裝的URL添加「Localhost:5000 /」。

function displayEvent(array,i){ 


    var image_url = array[i].calEvent.thumbImage.url; 
    var image =new Image(); 
    var hostname = location.hostname; 

    toronto_host = hostname.replace("localhost","app.toronto.ca") + 
    image_url; 
    alert(toronto_host); //this give me pull URL path// 

    image.src = toronto_host; 
    alert(image.src); 
    // this gives localhost:5000/what_i_had_in_toronto_host// 


    document.getElementById("party_picture").appendChild(image); 


}; 

,因爲沒有圖像路徑與http://localhost:5000/開始...我不能當我測試的網站上使用任何圖像。

任何方式我可以分配圖像src與正確的URL沒有localhost部分?

謝謝!

+0

我認爲問題在於你在'location.hostname'上調用'replace'。試試這個:'toronto_host =(hostname + image_url).replace(「localhost」,「app.toronto.ca」);' –

+0

嗨Rob,你的方法爲我返回相同的字符串。我的主要問題是不會自動包含http:// localhost:5000被添加到以下代碼中,即image.src = toronto_host,因此無論如何,image.src都會添加該主機名,因爲這是'src'需要的內容? –

回答

2

如果您沒有提供完整的URL(在您的情況下您提供除協議外的所有內容),則圖像src屬性將始終附加本地主機(或源自頁面的起始位置)。

toronto_host = hostname.replace("localhost","//app.toronto.ca") + 
image_url; 
              //^appending '//' before your 
              // location will force the browser 
              // to set the protocol to the current 
              // one of the page. 

這會使您的img.src按預期運行。

+0

啊哈我假設src是問題,不知道我可以添加//,救生員謝謝你! –