【问题标题】:Displaying image from website URL (json) to display locally in localhost显示来自网站 URL (json) 的图像以在 localhost 本地显示
【发布时间】:2017-08-11 19:20:50
【问题描述】:

我有 json 提要,它给了我缩略图 url。 这会返回类似 /webapps/CC/fileAPI/edc_eventcal/Celebrations_Todmorden%20Mills%20Harvest%20Festival_th__Vb2eHh-nEpJ8xLLEU5UFw.png 的网址

现在,在 /webapps/ 之前,它需要“app.toronto.ca”来获取完整路径。所以我像这样将“localhost”替换为“app.toronto.ca”。它为我提供了完整的图像路径。

现在,问题在于,即使我检索到完整的 URL,image.src 语法仍会强制计算机将“Localhost:5000/”添加到我完美组合的 URL 中。

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/ 开头...我在测试站点时无法使用任何图像。

有什么方法可以在没有 localhost 部分的情况下为图像 src 分配正确的 url?

谢谢!

【问题讨论】:

  • 我认为问题在于您在location.hostname 上致电replace。试试这个:toronto_host = (hostname + image_url).replace("localhost","app.toronto.ca");
  • 嘿 Rob,你的方法为我返回了相同的字符串。我的主要问题是不会自动将localhost:5000 添加到以下代码中,即 image.src = toronto_host 所以无论如何,image.src 都会添加该主机名,因为这就是“src”所需要的?

标签: javascript json hostname imagesource


【解决方案1】:

如果您不提供完整的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 行为符合预期。

【讨论】:

  • 啊哈哈,我认为 src 是问题,不知道我可以在上面添加//,救命,谢谢!
猜你喜欢
  • 2021-12-08
  • 2019-06-18
  • 2020-08-02
  • 2014-06-04
  • 2016-03-11
  • 2020-01-23
  • 2012-11-30
  • 2012-07-14
相关资源
最近更新 更多