简体   繁体   中英

JSON with PHP issue

Hello all just a bit stuck on this issue.

PHP5 is enabled. Just wondering on where I am going wrong, or the best way to detect an error. Here the first part, its the javascript code that works on a .html page:

<script type="text/javascript">
var  obj1 = {name:"Wayne", age:32, location:"Ireland"};
var  obj2 = {name:"Robert", age:25, location:"Ireland"};
var  obj3 = {name:"Chris", age:26, location:"Jama"};

var  classC3 = {student1:obj1, student2:obj2, student:obj3};

document.write(obj1.name + "<br>");
document.write(classC3.student2.name + "<br>");
</script>

The next part is where I am trying to run it with .PHP in the filefile

<html>
<head>
</head>

<body>

<?php
echo '<script type=\"text/javascript\">';
echo 'var  obj1 = {name:\"Wayne\", age:32, location:\"Ireland\"};';
echo 'var  obj2 = {name:\"Robert\", age:25, location:\"Ireland\"};';
echo 'var  obj3 = {name:\"Chris\", age:26, location:"Jama\"};';

echo 'var  classC3 = {student1:obj1, student2:obj2, student:obj3};';

echo 'document.write(obj1.name + \"<br>\");';
echo 'document.write(classC3.student2.name + \"<br>\");';
echo '</script>';
?>

</body>
</html>

Any idea's?

If you have double-quotes inside single-quotes, you don't have to escape them in PHP. By including them, you're creating invalid javascript. Remove the backslashes (or include one before Jama in obj3 and put all your PHP strings in double-quotes) and you should be okay.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM