前两天在组内做了一个小小的分享,关乎跨域处理,除了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>