工作中遇到的js跨域问题总结

起因:之前在做一个项目的时候有这样一个问题,127.0.0.1域名上的一个页面A.html,需要访问127.0.0.2域名上B.html页面中的一个方法。这就涉及到JS跨域访问了,通过查阅资料,得以解决,现总结一下。

具体问题:在A.html页面有一个下载按钮,当点击下载的时候,要访问B.html页面的方法,然后下载资源,苦苦寻找,终得良方。

良方如下:

     第一步  在A.html页面里面创建一个  iframe   ,

   //导出按钮
    $("#导出").click(function () {

        exec_iframe()

    });

    //跨域访问execB.html页面
    function exec_iframe() {
        if (typeof (exec_obj) == 'undefined') {
            exec_obj = document.createElement('iframe');
            exec_obj.name = 'tmp_frame';
            exec_obj.src = "http://127.0.0.2:8001"+'/execB.html';
            exec_obj.style.display = 'none';
            document.body.appendChild(exec_obj);
        } else {
            exec_obj.src = "http://127.0.0.2:8001"+'/execB.html';
        }
    }

  

   <iframe id="BpageId" name="myframe" src="http://127.0.0.2:8001/B.html" frameborder="0" scrolling="auto" style="width: 100%; height: 327px;"></iframe>                         

 第二步  创建B.html, execB.html页面,这两个页面都属于127.0.0.2:8001域下的页面,两个页面的内容如下

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <title> exec iframe function </title>
 </head>
     
 <body>
	<script type="text/javascript">
	    parent.window.myframe.downFile(); // execute parent myframe fIframe function
	</script>
 </body>
</html>

  

  B.html

 function downFile()

    {   下载  
    
}    

  

  

  如此一来,便可解决,闲的没事,写写博客!!!

猜你喜欢

转载自www.cnblogs.com/txqx/p/10869459.html