2017-08-11 140 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是问题,不知道我可以添加//,救生员谢谢你! –