PHP中JSON的跨域调用

主调文件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。

原文地址:https://www.cnblogs.com/Ann-wxp/p/4599670.html