JSON跨域数据调用

由于安全性问题,AJAX不支持跨域调用,这样要调用不同域名下的数据,比较麻烦。跨域数据调用除了常见的JSONP(可以参考:jsonp 跨域请求数据基本思路) 还可以使用script来调用:

主调文件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' => '陈毅鑫',    
    'nick' => '深空',    
    '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这么简单易用而且好用,还等什么呢?

Tags: PHP, json

添加新评论