参考资料:http://www.cnblogs.com/chopper/archive/2012/03/24/2403945.html
测试依赖条件:
项目eetopinOfficial 在hosts绑定 www.eetopin.com域名
项目sns 在hosts绑定sns.com域名
测试代码文件及源码:
eetopinOfficial/testCookie.php
<?php
header('Content-type: application/json');
//获取回调函数名
$callback = $_GET ['callback'];
$value = $_GET['name'];
//setcookie("name", "", time() - 3600);
setcookie('name', $value, time()+3600*24*30, '/','.eetopin.com', $_SERVER['SERVER_PORT']==443?1:0);
$json = "{\"name\":\"add cookie success $callback $value\"}";
echo $callback . "(" . $json . ")";
eetopinOfficial/testJsonp.php
<?php
header('Content-type: application/json');
//获取回调函数名
$callback = $_REQUEST ['callback'];
if (isset($_COOKIE["name"])){
$name = $_COOKIE["name"];
}else{
$name = "chopper";
}
//json数据
$json = "{\"name\":\"$name\",\"sex\":\"man\"}";
//echo $json;
//echo $callback;
//输出:回调函数名(json数据)
echo $callback . "(" . $json . ")";
//echo $callback ."($json)";
sns/testCookie.php
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$.getJSON("http://www.eetopin.com/testCookie.php?name=lunzi30108&callback=?",function(data){
alert(data.name);
});
</script>
sns/testJsonp.php
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$.getJSON("http://www.eetopin.com/testJsonp.php?callback=?",function(data){
alert(data.name + " is a a" + data.sex);
});
</script>
测试步骤:
1、http://sns.com/testCookie.php
2、http://sns.com/testJsonp.php