Search code examples
javascriptjsonhostnameimagesource

Displaying image from website URL (json) to display locally in localhost


I have json feed that gives me thumbimage url. This returns url like /webapps/CC/fileAPI/edc_eventcal/Celebrations_Todmorden%20Mills%20Harvest%20Festival_th__Vb2eHh-nEpJ8xLLEU5UFw.png

Now, before /webapps/ It needs "app.toronto.ca" to get the full path. So I've replaced "localhost" into "app.toronto.ca" like so. And it gives me full path to image.

Now, the trouble is that, even though I retrieve full URL, image.src syntax will still force computer to add 'Localhost:5000/' to my perfectly assembled 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);


};

since no image path starts with http://localhost:5000/... i can't use any image while i'm testing the site.

Any way i could assign image src with the correct url without localhost part?

thank you!


Solution

  • Image src attribute will always append the localhost ( or where the page originates from ), if you don't provide a complete URL ( in your case you provide everything except the protocol ).

    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.
    

    This will make your img.src to behave as expected.