您的位置:首页 > 编程语言 > PHP开发

PHP中JSON的跨域调用

2015-06-25 12:13 555 查看
主调文件index.html

<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.php

<?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中,这样一次跨域数据交互就完成了。

注意:当json数据值中包含中文时,记得使用PHP编码转化iconv函数进行编码转化iconv('gb2312','utf-8','笑哈哈'),将中文编码gb2312转化为utf-8。

json_encode()函数只能接受 UTF-8 编码的数据,否者中文部分会变为NULL。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: