Search code examples
jqueryjsonhref

Change href value of a link by fetching URL from JSON file (jQuery)


I have a very simple .JSON file called 'screen.json' as follows:

[
    {
        "link": "http://localhost:8888/screen/screen1.png"
    }
]

And a very simple HTML link:

<a id="screen" href="#"></a>

What I would like to do is, on page load, using jQuery, fetch the "link" value from the .JSON file and put it inside the href="" tag where the # symbol is.

$(document).ready(function() {

}

I know it will involve an ajax call in the jQuery above, to get the string from the .json file and then place it inside the 'href=""' tag, but I don't know how to do this.

Could anyone help me? Cheers! :)


Solution

  • $(document).ready(function(e) {
        $.get(url, function(response) {
           //response = JSON.parse(response);//use this in case you are not getting json in response to parse response
           //Change href Value use attr()
           $('#screen').attr('href', response[0]['link']); 
        });
    });