Quantcast
Channel: CodeIgniter Forums - All Forums
Viewing all articles
Browse latest Browse all 14114

Using JSON in data attributes with JS

$
0
0
I don't know if it's considered bad practice, or if it's the way everyone does it, but I find myself inserting JSON data into HTML element attributes all the time. So, for instance:

PHP Code:
foreach( $query->result_array() as $row )
    
$arr[] = (object) array_map'html_escape'$row );

$json json_encode$arr );

$json_string str_replace([
    
'"',
    
''',
    
'& #039;' // space here for codeigniter forum
], [
    
'\u0022',
    
'\u0027',
    
'\u0027'
], $json ); 

Now I know that json_encode has options like JSON_HEX_APOS and JSON_HEX_QUOT, but I also want to use html_escape() which is why I'm using str_replace the way I am. This allows me to do this:


PHP Code:
echo '<div data-json=\'' $json_string '\'>'

Then later in my json I can use JSON.parse() on the contents of that data-json attribute.

What are your thoughts here? Is there a better way?

Viewing all articles
Browse latest Browse all 14114


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>