NoviceDeveloper NoviceDeveloper - 9 days ago 6
HTML Question

How to access an html content json object via URL

So for example, if my URL is www.someurlsomewhere.com/GetItemById?Id=5 and my response is an array of json objects.

Success: true
Html: "<html><body>test</body></html>"
FileName: "test.html"


How do I say www.someurlsomewhere.com/GetItemById?Id=5?data=Html to make it act like a link to the Html part of my json object within response.

Answer

You are talking about Query Parameters or URL Parameters. The correct format for adding multiple parameters is separating them with &. Your URL would look similar to: www.someurlsomewhere.com/GetItemByID?Id=5&data=html.

To extract that information, you would need to parse the URL parameters and then serve up the information that you want based on the data. This can be done server side or client side. Look up URL Parameter Parsing to get ideas on how to do it in the language of your choice. One of the examples that comes up in JavaScript is How can I get query string values in JavaScript?.

After you've parsed the URL parameter out that you want, now you need to render it to the page. Look up Parsing HTML. I'm going to assume you're doing it in javascript, just to give you an example of parsing:

var data = {
    success: true,
    html: "<html><body>test</body></html>",
    filename: "test.html"
}
var el = document.createElement('html'); //creates a temporary dummy element to append to the page... although if you already have something on the page, you may use that container
el.innerHTML = data.html; //here you're selecting the element and adding a string of HTML to it

There are a lot of unknowns about what you're asking. But here is a potential client side solution that retrieves the URL parameter then passes it as HTML to the DOM.

<script>
    //Assuming your URL looks like this:
    // www.someurlsomewhere.com/GetItemByID?Id=5&src=html
    function getParameterByName(name, url) {
    if (!url) {
      url = window.location.href;
    }
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
    }

    var src = getParameterByName('src'); //Use your parameter function to retrieve the src parameter from the URL. Currently src = 'html'

    //This is a representation of your JSON payload that you're receiving from somewhere
    var data = {
        success: true,
        html: "<html><body>test</body></html>",
        filename: "test.html"
    }

    var el = document.createElement('html'); //creates a temporary dummy element to append to the page... although if you already have something on the page, you may use that container
    el.innerHTML = data[src]; //here you're selecting the element and adding a string of HTML to it. This would translate to data.html
</script>