主調文件index.htmljavascript
<script type="text/javascript"> function getProfile(str) { var arr = str; document.getElementById('nick').innerHTML = arr.nick; } </script> <body><div id="nick"></div></body> <script type="text/javascript" src="http://www.openphp.cn/demo/profile.php"></script>
被調文件profile.phpphp
<?php $arr = array( 'name' =>iconv('gb2312','utf-8','笑哈哈'), 'nick' => iconv('gb2312', 'utf-8','哈哈'), 'contact' => array( 'email' => 'shenkong at qq dot com', 'website' => 'http://www.chinaz.com', ) ); $json_string = json_encode($arr); echo "getProfile($json_string)"; ?>
顯然,當index.html調用profile.php時,JSON字符串生成,並做爲參數傳入getProfile,而後將暱稱插入到div中,這樣一次跨域數據交互就完成了。html
注意:當json數據值中包含中文時,記得使用PHP編碼轉化iconv函數進行編碼轉化iconv('gb2312','utf-8','笑哈哈'),將中文編碼gb2312轉化爲utf-8。java
json_encode()函數只能接受 UTF-8 編碼的數據,否者中文部分會變爲NULL。web