跨域处理

前两天在组内做了一个小小的分享,关乎跨域处理,除了iframe跨域以及h5 设置响应头跨域外主要是jsonp以及反向代理的介绍。

附上前端代码,jsonp方法写的比较简化,可以更多定制,另外为了方便,把js写在html内了。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>Document</title>
</head>
<body>
    <div class="btns">
        <button>ajax发起同域请求</button>
        <button>ajax发起跨域请求</button>
        <button>jsonp发起跨域请求</button>
        <button>ajax通过反向代理发起跨域请求</button>
    </div>
    <div>
        <h4>response</h4>
        <div class="response"></div>
    </div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var testFn = new function(){
    var me = this;
    
    me.fn0 = function(){
        $.get("test.php?msg=test",me.callback);
    }

    me.fn1 = function(){
        $.get("http://www.testb.com/test.php?msg=test")
    }

    me.fn2 = function(){
        me.jsonp("http://www.testb.com/testjsonp.php?msg=test",me.callback);
    }

    me.fn3 = function(){
        $.get("http://www.testa.com/api/test.php?msg=test",me.callback)
    }

    me.jsonp = (function(){
        var id = +(Math.random()+"").split(".")[1];
        return function(url,callback){
            var cb = "cb"+(++id),
                _url = url += "&cb=testFn."+cb+"&_="+(new Date).getTime(),
                script = document.createElement("script");
                script.src = _url;

            me[cb] = function(){
                callback.apply(null,arguments);
                delete me[cb];
            }

            document.getElementsByTagName("head")[0].appendChild(script);
            script.parentNode.removeChild(script);
        }        
    })();

    me.callback = function(r){
        $(".response").html(r);
    }

    me.init = function(){
        $(".btns").on("click","button",function(){
            me["fn"+$(this).index()]();
        });
    }
}

testFn.init();
</script>
</body>
</html>

Apache的反向代理配置

<VirtualHost *:80>

   ServerName www.testa.com

   DocumentRoot "D:\test\a"

   <Directory "D:\test\a">
     Options Indexes
     Order deny,allow
     Allow from all
   </Directory>
ProxyRequests Off
<Proxy *>
Order deny,allow
Allow from all
</Proxy>
ProxyPass /api/ http://www.testb.com/
ProxyPassReverse /api/ http://www.testb.com/

</VirtualHost>

 

转载于:https://www.cnblogs.com/anson0415/p/5278585.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值