I need to generate the following script using PHP and json_encode().
var obj= {
o1:123,
o2: {
o3: 456,
o4: function() {return $( "#myID" ).val();}
}
}
My attempt to do so is as follows.
<?php
$a=array(
'o1'=>123,
'o2'=>array(
'o3'=>456,
'o4'=>'function() {return $( "#myID" ).val();}'
)
);
$json=json_encode($a);
?>
<script type="text/javascript">
<?php echo("var obj={$json};");?>
console.log(obj);
</script>
The resultant output is as follows. The quotes around the properties poses no issues, however, the quotes around the JavaScript renders it as a string and not JavaScript. I obviously can't not quote the JavaScript in the array as it will result in malformed JSON.
How can I include JavaScript in PHP's json_encode()?
var obj={
"o1":123,
"o2":{
"o3":456,
"o4":"function() {return $( \"#username\" ).val();}"
}
};
