Clay Banks
Clay Banks

Reputation: 4581

Creating an href on Returned JSON Data

I have some basic JSON data returned from an ajax request which populates a table

JSON

  {"data": {
      "id": "100",
      "name": "file name",
      "url": "www.somesite.com/abc/xyz",
       //etc...
   }  }

Table

ID   | 100
name | file name
url  | www.somesite.com/abc/xyz

I'd like to create a dynamic anchor tag with the url value as the href - I know this can be done within a callback function once the data is returned, but I'm wondering if there is a simpler (or the simplest) method to accomplish this

Desired table output

ID   | 100
name | file name
url  | Click Here! //obviously the link to mysite.com/abc/xyz

Upvotes: 0

Views: 3339

Answers (1)

Jim Buck
Jim Buck

Reputation: 2444

Every single AJAX request is asynchronous, so there is no other option but to handle it in a callback (traditional or wrapped in promise).

This is how I would do it:

// Get data is some function that makes the request and accepts a callback...
getData(function(data){
    // Build an anchor tag...
    var link = document.createElement('a');
    link.setAttribute('href', data.url);
    link.innerHTML = 'Click Here!';

    // Add it to the element on the page.
    var table = document.getElementById("table");
    table.appendChild(aTag);
});

Make sure you modify the code to add it to the page, it will be different based on your markup.

Inspired By: How to add anchor tags dynamically to a div in Javascript?

Upvotes: 4

Related Questions