PHP code:
<
html
>
<
head
>
<
title
>
Json Test
</
title
>
<
SCRIPT src
=
"jquery
.js"
>
</SCRIPT>
<SCRIPT src="jquery.json.js"></SCRIPT>
<script>
$(document).ready(function(){
var data = new Object();
data.hello = "Hello";
data.world = 'World';
data.worked = " it worked ";
data.somebool = true;
data.array = new Array("he/"ll/"o", '"World"');
var dataString = $.toJSON(data);
$.post('phpfile.php', {data: dataString}, function(res){
var obj = $.evalJSON(res);
if(obj.somebool === true)
$("#result").html(obj.hello + ' ' + obj.array[1] + obj.worked + ". Message from PHP: "+obj.php_message);
});
});
</script>
<body>
<div id="result"></div>
</body>
We initialize some test data, use the $. tojson method to encode it, and use the $. Post method to send it to phpfile. php:
Copy the PHP content to the clipboard.
PHP code:
$res =
json_decode
(
$_REQUEST
[
'data'
],
true
);
$res
[
"php_message"
] =
"I am PHP"
;
echo
json_encode
(
$res
);
Note that the last parameter of json_decode will return a stdobject object, but this is not the data type we want in this simple test.
The output result is as follows:
Hello "world" It worked. Message from PHP: I am PHP
Very good!