0

For small amounts of textual info ( Control Messages ) I send what I call bullets (Same syntax as HTML comments ) along with my page during ajax calls. For example

<!--Control Message--><html> all my page here</html>

I then parse the "Bullet" out before rendering the page...even though I don't really have to.

For more data, say 5 variables, I plan on json_encoding it...and sending it with the page as well.

How are others demarcating and extracting the structured data / json strings from html. I could just put it in a "bullet" like below and extract it out...but my guess is there is a more "proper" way to do this.

<!--json string here--><html> all my page here</html>

2 Answers 2

5

If you are passing this via AJAX, just embed the HTML in the JSON and parse that JSON as a whole:

{
    "html":"<html>...</html>",
    "other_data":...,
    "some_more_data":...
}

//access it later:
data.html
data.other_data
data.some_more_data

If this data loaded with the page, store the data in a variable instead:

<html>
    <head>
        <script>
            var data = <?= json_encode($data) ?>;
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, but it's no problem for PHP: json_decode(). php.net/manual/en/function.json-decode.php
@HiroProtagonist json_encode, afaik, does the necessary escaping to prevent syntax self-destruction. However, when parsed, it's up to you on how the parsed data was escaped.
Ended up using array pushes for each element and then encoding the array.
1

If the data is contextual with the HTML, it would be good to send them as data tags within the HTML?

<html data-value="{name:value}">
    <body>
        <div data-div="{name:value}">
    </body>
</html>

3 Comments

Personally, I keep my application client view structure separate from the data as this makes writing the data simpler...but a good idea for other styles of programming.
+ I send static data and dynamic data separately...as a design choice..so dynamic data is inserted after static data ( which may be cached locally )
In my opinion; the driving factor should be "is the data contextual?" eg: I want to remember a timestamp on when a chart was refreshed... I put it on the div holding the chart.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.