Reputation: 407
I'm using the combination of json_encode (PHP) and JSON.parser (Javascript from json.org) for passing a JSON object from PHP to Javascript, the JSON object may have quotes and double quotes so I'm using addslashes() function in PHP. This combination work well in Firefox but not in other browsers like Safari, Chrome or Internet Explorer. This is the code:
<?php
$json =array('n' => count($arrayEx), 'items' => array());
foreach($arrayEx as $item)
{
$json['items'][]=array( 'property1' => addslashes($item['property1']),
'property2' =>addslashes($item['property2'])
);
}
$json_string = json_encode($json);
?>
<script>
var json_string= '<? echo $json_string; ?>';
var json_object = JSON.parse(json_string); //Fail in this line
</script>
Fail with error message "String literal not ended".
Thanks
Upvotes: 0
Views: 1205
Reputation: 655609
Leave the quotes out and it should work:
var json_string = <?php echo $json_string; ?>;
The string returned by json_encode
already is a valid JavaScript expression and thus doesn’t need any further declarations.
Upvotes: 2