View Single Post
Old 06-06-2012, 02:57 AM   PM User | #4
DaveyErwin
Regular Coder

 
Join Date: Aug 2010
Posts: 810
Thanks: 12
Thanked 168 Times in 166 Posts
DaveyErwin is on a distinguished road
this works on the same server ...

Code:
<!doctype html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<title></title>
</head>
<body>
<script> 
req = new XMLHttpRequest;
req.open("GET","json.php",false);
req.send(null);
alert(JSON.parse(req.responseText).a);// alerts "I'm a!"

</script> 
</body>
</html>
no need to wrap the json
with a function call ...

json.php ...

PHP Code:
<?php
class Foo
{
    public 
$a "I'm a!";
    public 
$b "I'm b!";
    public 
$c;
}
$obj = new Foo();
echo 
json_encode($obj);

?>
okay here is another way
this will work on remote server ...

Code:
<!doctype html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<title></title>
</head>
<body>
<script>
function callback(resp){alert(resp.a)}// alerts "I'm a!"
</script>
<script src = "json.php"></script> 
</body>
</html>
the json.php

PHP Code:
<?php
class Foo
{
    public 
$a "I'm a!";
    public 
$b "I'm b!";
    public 
$c;
}
$obj = new Foo();
echo 
"callback(".json_encode($obj).")";

?>

Last edited by DaveyErwin; 06-06-2012 at 03:23 AM..
DaveyErwin is offline   Reply With Quote