码迷,mamicode.com
首页 > 其他好文 > 详细

(十) ng-inlude指令加载页面失败的原因和解决方法

时间:2015-02-05 21:55:05      阅读:278      评论:0      收藏:0      [点我收藏+]

标签:ng-include跨域访问   ng-include加载失败   

angularjs中提供的ng-include指令,很类似于JSP中的<jsp:include>用来将多个子页面合并到同一个父页面中,避免父页面过大,可读性差,不好维护。

父页面parent.html代码如下:

<html>
  <head>
    <script src="angular-1.2.2/angular.js"></script>
	<script>
	 function rootController($scope,$rootScope,$injector)
	 {
		$rootScope.name = "aty";
		$rootScope.age = 25;
	 }
	</script>
  </head>
  <body  ng-app ng-controller="rootController">
        <h1>Hello, {{name}}!</h1>
        <h1>Hello, {{age}}!</h1>
	
	<div id="included" ng-include="'child.html'">
            <input type="button" value="2"/>
        </div>
  </body>
</html>

被包含的子页面child.html代码如下:

 <div>
        <h1>included, {{name}}!</h1>
        <h1>included, {{age}}!</h1>
 </div>


我用IE11和Chrome39运行parent.html,发现child.html页面不能包含到parent.html中。IE下报错信息如下:

Error: 拒绝访问。
   at Anonymous function (file:///D:/learn/angular-1.2.2/angular.js:7852:7)
   at sendReq (file:///D:/learn/angular-1.2.2/angular.js:7720:9)
   at serverRequest (file:///D:/learn/angular-1.2.2/angular.js:7454:9)

chrome下报错信息如下:

XMLHttpRequest cannot load file:///D:/learn/include.html. 
Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'file:///D:/learn/include.html'.


IE下的提示有些晦涩,不过chrome提示很明显:不能跨域访问。通过上面的错误提示,可以看到:使用ng-include指令的时候,会用到AJAX请求XMLHttpRequest。但是我们是直接用浏览器打开的parent.html,并没有通过web容器访问,所以存在跨域访问问题,加载child.html也就失败了。解决办法很简单:将代码部署到tomcat等web容器下,通过http访问即可。


平时在练习javascript或者是JS框架的时候,一版都是使用比较轻量级的工具,不会使用像Eclipse之类IDE,我一般使用Notepad++编写js代码。Notepad++可以方便地调用本机安装的浏览器。像ng-include这样的指令,必须要有web容器的支持。可以使用前端开发神器webstorm,该工具运行html的时候,会自动启动内置的web容器,这样ng-include指令就不会报错了。 

 

 

 


 

(十) ng-inlude指令加载页面失败的原因和解决方法

标签:ng-include跨域访问   ng-include加载失败   

原文地址:http://blog.csdn.net/aitangyong/article/details/43490117

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!