Welcome Guest, Not a member yet? Register   Sign In
Using JSON in data attributes with JS
#1

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?
Reply


Messages In This Thread
Using JSON in data attributes with JS - by skunkbad - 11-14-2017, 02:16 PM



Theme © iAndrew 2016 - Forum software by © MyBB