前兩天在組內作了一個小小的分享,關乎跨域處理,除了iframe跨域以及h5 設置響應頭跨域外主要是jsonp以及反向代理的介紹。javascript
附上前端代碼,jsonp方法寫的比較簡化,能夠更多定製,另外爲了方便,把js寫在html內了。php
<!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的反向代理配置html
<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>