php跨域调用json的例子

时间:2013-11-13    点击:146   

JSON和XML没什么太大区别,不过JSON有一个更大范围的应用,那就是,跨域的数据调用。由于安全性问题,AJAX不支持跨域调用,这样要调用不同域名下的数据,很麻烦。下面这个例子,足以展示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' => 'tanteng', 
    'nick' => 'pony', 
    'contact' => array( 
        'email' => 'a@gmail.com', 
        'website' => 'http://aa.sinaapp.com', 
    ) 
); 
$json_string = json_encode($arr); 
echo "getProfile($json_string)"; 
?>

当index.html调用profile.php时,JSON字符串生成,并作为参数传入getProfile,然后将昵称插入到div中,这样一次跨域数据交互就完成了,是不是特别简单。

JS:window.onload的使用介绍
JQuery each打印JS对象的方法
Jquery 数组操作大全个人总结
JS保存和删除cookie操作 判断cookie是否存在
js 判断上传文件大小及格式代码
> 返回     
地址:上海市普陀区胶州路941号长久商务中心 电话: QQ:
© Copyright 2012 上海网络 Product All Rights Reserved