PHP代碼:
<
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>
</head>
<body>
<div id="result"></div>
</body>
</html>
我們初始化一些測試資料,使用$.toJSON方法編碼它和使用$.post方法把它傳送給phpfile.php:
複製PHP內容到剪貼簿
PHP代碼:
$res =
json_decode
(
$_REQUEST
[
'data'
],
true
);
$res
[
"php_message"
] =
"I am PHP"
;
echo
json_encode
(
$res
);
注意json_decode的最後一個參數,忽略它將會返回一個名為stdObject對象,但這不是我們在這個簡單測試中想得到的資料類型。
最後輸出的結果:
Hello "World" it worked . Message from PHP: I am PHP
非常好!