码迷,mamicode.com
首页 > Web开发 > 详细

PHP中JSON的跨域调用

时间:2015-06-25 13:55:19      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

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

PHP中JSON的跨域调用

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!