设计模式知识连载(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>
相关文章推荐
- 设计模式知识连载(23)---桥接模式:
- 设计模式知识连载(37)---链模式:
- 设计模式知识连载(38)---委托模式:
- 设计模式知识连载(40)---节流模式:
- 设计模式知识连载(42)---惰性模式:
- 设计模式知识连载(1)---函数的书写方式
- 设计模式知识连载(3)---封装_2:闭包
- 设计模式知识连载(50)---MVVM模式:
- 设计模式知识连载(2)---封装_1
- 设计模式知识连载(7)---继承_3:优点结合-组合继承
- 设计模式知识连载(22)---装饰者模式:
- 设计模式知识连载(35)---迭代器模式:
- 设计模式知识连载(25)---享元模式:
- 设计模式知识连载(19)---外观模式:
- JAVA知识之设计模式(一):代理模式
- 设计模式知识连载(4)---封装_3:创建对象的安全模式
- 设计模式知识连载(27)---观察者模式:
- 设计模式知识连载(28)---状态模式:
- 设计模式知识连载(39)---数据访问对象模式---本地存储DAO
- 设计模式知识连载(43)---参与者模式: