您的位置:首页 > 其它

设计模式知识连载(21)---代理模式:

2017-12-19 16:38 561 查看
<body>

<h3>设计模式知识连载(21)---代理模式:</h3>
<p>
由于一个对象不能直接引用另外一个对象,所以需要通过代理对象在这两个对象之间起到中介作用。
【暂无细究,用到再琢磨】
</p>

<script type="text/javascript">

/**
*   案例一:站长统计,方式一:初始
*/
//统计代理
var Count = (function () {
// 缓存图片
var img = new Image() ;

// 返回统计函数
return function(param) {
// 统计请求字符串
var str = 'htpp://www.count.com/a.gif' ;

// 拼接请求字符串
for(var i in param) {
str += i + '=' + param[i] ;
} ;

// 发送统计请求
_img.src = str ;
}
})() ;
// 测试用例,统计num
Count({num : 10}) ;

/**
*   案例二:JSONP,方式一:初始
*/
// 前端浏览器页面
<s-c-r-i-p-t type = 'text/javascript'>
//回调函数,打印出请求数据与响应数据
function jsonpCallBack(req, res) {
console.log(req, res) ;
}
</s-c-r-i-p-t>
<s-c-r-i-p-t type="text/javascript" src = 'http://localhost/test/jsonp.php?callback=jsonpCallBack&data=getJsonpData'></s-c-r-i-p-t>

// 另外一个域下服务器请求接口
<?php
/*后端获取请求字段数据,并生成返回内容*/
$data = $_GET['data'] ;
$callback = $_GET['callback'] ;
echo $callback.'("success","'.$data.'")' ;
?>

/**
*   案例三:代理模板,方式一:初始
*/
// X域中被代理页面A
<s-c-r-i-p-t type = 'text/javascript'>
function callback(data) {
console.log('成功接收数据:', data) ;
} ;
</s-c-r-i-p-t>
<iframe name = 'proxyIframe' id = 'proxyIframe' src = ''></iframe>
<form action = 'http://localhost/test/proxy.php' method = 'post'
target='proxyIframe'>
<input type = 'text' name = 'callback' value = 'callback'>
<input type = 'text' name = 'proxy' value = 'http://localhost:8080/proxy.html'>
<input type = 'submit' value = '提交'>
</form>

// X域中被代理页面B
<s-c-r-i-p-t type = 'text/javascript'>
// 页面加载后执行
window.onload = function() {
// 如果不在A页面中返回,不执行
if(top == self) {
return ;
} ;

// 获取并解析searcher中的数据
var arr = localhost.search.substr(1).split('&') ;
var fn ;
var args ;

// 预定义函数名称以及参数集
for(var i = 0, len = arr.length, item; i < len; i++) {
// 解析searcher中的每组数据
item = arr[i].split('=') ;
// 判断是否为回调函数
if(item[0] == 'callback') {
// 设置回调函数
fn = item[1] ;
// 判断是否是参数集
}else if(item[0] == 'arg') {
// 设置参数集
args = item[1];
}
} ;
try{
// 执行A页面中预设的回调函数
eval('top.' + fn + '("'+ args +'")') ;
}catch(e) {}
}
</s-c-r-i-p-t>

// Y域中被请求的接口文件C
<?php
$proxy = $_POST['proxy'] ;
$callback = $_POST['callback'] ;
header('Location:'.$proxy.'?callback='.$callback.'&arg=success') ;
?>
</script>

</body>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息